我需要在 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)
请注意,在第三个示例中,虽然它没有伤害,的字符串的最大长度
<= “this is a C string”的长度
则“+1”并不是真正必要的。
这是因为当 sizeof() 用于创建 MAX_AVAIL_LEN 时,
它在其对字符串
文字长度的评估中包含了 NULL 字符。(即 19)尽管如此,在为 C 字符串分配内存时,通常以这种方式编写它,
以明确显示在内存分配期间已考虑了 NULL 字符的空间。
注 2也是第三个示例,必须在使用free(str);
完毕后使用str
。
在此处查找有关 C 字符串的更多信息。