【发布时间】:2022-01-13 05:20:10
【问题描述】:
我正在尝试将 C 中的字符串(使用 string.h 库)转换为 const char 数组。
int len = sizeof(the_string);
const char *char_array = malloc(len);
strcpy(char_array, the_string);
我仔细研究了 string.h 方法文件并用谷歌搜索了它,但 C++ 中不断出现问题。任何建议将不胜感激,谢谢!!!
【问题讨论】:
-
您可能会重新阅读有关
const关键字含义的学习资料。您不能将任何内容复制到声明为const的变量中。这正是const的意义所在。您也不能将指向const区域的指针传递给free。 -
如前所述,
const本质上是告诉编译器“不得修改内容”,这就是此分配失败的原因。请问你为什么坚持const char那里?请注意,编译器会自动转换为const *,但不会返回。 (因此,使用const *调用一个采用const char *的函数非常好。 -
这能回答你的问题吗? c make a copy of an array of const structs
-
您收到的错误消息的哪一部分需要帮助理解?
-
@Kozmotronik: 忽略
const,如果the_string是使用char the_string[] = "the string's value";定义的(作为一个数组),那么sizeof(the_string)很好,并且在计数中包含空字节。如果它是使用char *the_string = "the string's value";定义的,那么使用sizeof(the_string)是错误的——它返回指针的大小,而不是指针指向的字符串的长度。
标签: c pointers initialization declaration c-strings