我刚刚开始使用C编程语言来编写我的课程项目,而且我对C语言知之甚少.我已经使用C++一段时间了,我需要在C中找到c_str()函数的替代方法.我试图编码(在C中)类似于下面的c ++代码.我完全不知道如何做同样的事情.任何帮助是极大的赞赏.
void putVar(double* var,int N, string name, Engine *ep){
double row = N, col = N;
mxArray *matlab = mxCreateDoubleMatrix(row, col, mxREAL);
double *pa = mxGetPr(matlab);
memcpy(pa, var, sizeof(double)*row*col);
engPutVariable(ep, name.c_str() , matlab);
}
Run Code Online (Sandbox Code Playgroud)
我需要在C中找到c_str()函数的替代方法...
如上面的注释中所述,C没有字符串类型,但C确实使用了数组char,而当NULL终止时通常称为C字符串.
在C中创建字符串有很多种方法.以下是三种非常常见的方法:
给出以下内容 :(在此示例中为说明)
#define MAX_AVAIL_LEN sizeof("this is a C string") //sets MAX_AVAIL_LEN == 19
Run Code Online (Sandbox Code Playgroud)
1
char str[]="this is a C string";//will create the variable str,
//populate it with the string literal,
//and append with NULL.
//in this case str has space for 19 char,
//'this is a C string' plus a NULL
Run Code Online (Sandbox Code Playgroud)
2
char str[MAX_AVAIL_LEN]={0};//same as above, will hold
//only MAX_AVAIL_LEN - 1 chars for string
//leaving the last space for the NULL (19 total).
//first position is initialized with NULL
Run Code Online (Sandbox Code Playgroud)
3
char *str=0;
str = malloc(MAX_AVAIL_LEN +1);//Creates variable str,
//allocates memory sufficient for max available
//length for intended use +1 additional
//byte to contain NULL (20 total this time)
Run Code Online (Sandbox Code Playgroud)
注意,在该第三例子中,虽然它不伤害,
该"+1"是不是真的有必要如果的最大长度
中使用字符串是<=的长度"这是一个C字符串".
这是因为当在创建MAX_AVAIL_LEN时使用sizeof()时,
它在字符串
文字长度的评估中包含NULL字符.(即19)
尽管如此,在为C字符串分配内存
以明确显示在内存分配期间已考虑空字符的空间时,通常以这种方式编写它.
注2,也是第3个例子,必须在使用free(str);完毕后使用str.
在这里寻找更多的C字符串.