【问题标题】:Trying to copy a string into a const char * array in C试图将字符串复制到 C 中的 const char * 数组中
【发布时间】: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


【解决方案1】:

这个指针的声明

const char *char_array;

表示你不能使用指针改变指针指向的内存。

你可以让指针本身成为一个常量对象,比如

char * const char_array = malloc( some_size );

在这种情况下,您可能不会重新分配指针本身,但您可以更改指针指向的内存。

考虑到表达式sizeof(the_string) 没有多大意义,如果您要知道存储在字符数组中的字符串的长度,因为通常字符数组可能比其中存储的字符串大得多.相反,你应该写

size_t len = strlen( the_string );

在这样的声明中使用表达式 sizeof(the_string) 是有意义的

char the_string[] = "Hello";

即字符数组的大小由用作初始值设定项的字符串字面量的大小决定。

【讨论】:

  • 问题中没有显示the_string的定义。如果它是一个数组(const char the_string[] = "the value in the string";),那么sizeof(the_string) 正确地报告了数组的大小,包括终端空字节并且一切正常。如果它被定义为const char *the_string = "the value of the string"; 那么sizeof(the_string) 给出完全错误的答案。无论the_string 的定义方式如何,使用size_t len = strlen(the_string) + 1; 都会给出正确的大小,所以这是最好的——但+ 1 是至关重要的!
猜你喜欢
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多