简体   繁体   English

试图将字符串复制到 C 中的 const char * 数组中

[英]Trying to copy a string into a const char * array in C

I am trying to convert a string in C (using the string.h library) into a const char array.我正在尝试将 C 中的字符串(使用 string.h 库)转换为 const char 数组。

int len = sizeof(the_string);
const char *char_array = malloc(len);
strcpy(char_array, the_string);

I have pored through the string.h method file and googled it but things keep coming up in C++.我仔细研究了 string.h 方法文件并用谷歌搜索了它,但 C++ 中不断出现问题。 Any advice would be greatly appreciated, thank you!!!任何建议将不胜感激,谢谢!!!

This declaration of a pointer这个指针的声明

const char *char_array;

means that you may not change the memory pointed to by the pointer using the pointer.意味着您不能使用指针更改指针指向的 memory。

You could make the pointer itself a constant object like您可以使指针本身成为常量 object ,例如

char * const char_array = malloc( some_size );

In this case you may not reassign the pointer itself but you may change the memory pointed to by the pointer.在这种情况下,您可能不会重新分配指针本身,但您可以更改指针指向的 memory。

Take into account that the expression sizeof(the_string) does not make a great sense if you are going to know the length of a string stored in a character array because in general a character array can be much larger than the stored string in it.考虑到表达式sizeof(the_string)如果您要知道存储在字符数组中的字符串的长度没有多大意义,因为通常字符数组可能比其中存储的字符串大得多。 Instead you should write相反,你应该写

size_t len = strlen( the_string );

Using the expression sizeof(the_string) makes a sense in declarations such this在这样的声明中使用表达式 sizeof(the_string) 是有意义的

char the_string[] = "Hello";

that is when the size of a character array is determined by the size of a string literal used as an initializer.也就是说,字符数组的大小由用作初始值设定项的字符串文字的大小决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM