c中的c_str()等价物

时间:2014-07-16 19:15:26

标签: c char c-str

我刚刚开始使用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);
}

1 个答案:

答案 0 :(得分:6)

  

我需要在C ...

中找到c_str()函数的替代方法

如上面的评论中所述,C没有字符串类型,但C确实使用char的数组,而当NULL终止时通常称为 C字符串
在C中创建字符串有很多种方法。以下是三种非常常见的方法:

鉴于以下 :(在此示例中为了说明)

#define MAX_AVAIL_LEN sizeof("this is a C string") //sets MAX_AVAIL_LEN == 19

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 

<强> 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

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)

注意 ,在第3个示例中,虽然没有受伤,但是 &#34; + 1&#34;是不是真的必要如果最大长度为 要使用的字符串是&lt; =&#34的长度;这是一个C字符串&#34;。
这是因为当创建MAX_AVAIL_LEN时使用sizeof(),
它在字符串
的评估中包含NULL字符 字面长度。 (即19)
尽管如此,在为C字符串分配内存时,通常会这样写 显示显式在内存分配期间已考虑NULL字符的空间。

注意2 ,对于第3个示例,在使用free(str);完成后必须使用str

点击此处查看 more on C strings

相关问题