[英]Changing contents in array of character pointers
This seems like it should be easy but i've spent way too much time on it. 这似乎很容易,但是我花了太多时间在上面。 Hopefully someone can help.
希望有人可以提供帮助。
char *string_labels[5] = { "one", "two", "three", "four", "five" };
void myFunction(void)
{
//can print them just like expected
for(i=0; i < 5; i++)
{
printf("%s\n", string_labels[i]);
}
//how can i change the contents of one of the elements??
sprintf(string_labels[0], "xxx"); <-crashes
}
It crashes because it's in read-only memory. 由于它位于只读内存中,因此崩溃。 Try
尝试
char string_labels[][6] = { "one", "two", "three", "four", "five" };
sprintf(string_labels[0], "xxx");
To do this, you need to use a character array, so that you actually have some runtime-writable space to modify: 为此,您需要使用一个字符数组,以便实际上您有一些运行时可写的空间来进行修改:
char string_labels[][20] = { "one", "two", "three", "four", "five" };
void myFunction(void)
{
/* Printing works like before (could be improved, '5' is nasty). */
for(i=0; i < 5; i++)
{
printf("%s\n", string_labels[i]);
}
/* Now, modifying works too (could be improved, use snprintf() for instance. */
sprintf(string_labels[0], "xxx");
}
string_labels
is an array of char pointers pointing to string literals. string_labels
是指向字符串文字的char指针数组。 Since the string literals are read-only, any attempt to modify them leads to undefined behavior. 由于字符串文字是只读的,因此任何尝试修改它们的操作都会导致未定义的行为。
You can change the declaration of string_labels
as below to make your sprintf
work: 您可以如下更改
string_labels
的声明,以使sprintf
工作:
char string_labels[][6] = { "one", "two", "three", "four", "five" };
Each of string_labels[i]
points to a string literal, and attempting to modify the contents of a string literal invokes undefined behavior. 每个
string_labels[i]
指向一个字符串文字,并且尝试修改字符串文字的内容会调用未定义的行为。
You'll need to declare string_labels
as an array of arrays of char
, rather than as an array of pointers to char
: 您需要将
string_labels
声明为char
数组的数组,而不是char
的指针数组:
#define MAX_LABEL_LEN ... // however big the label can get + 0 terminator
char string_labels[][MAX_LABEL_LEN]={"one", "two", "three", "four", "five"};
This declares a 5-element array (size taken from the number of initializers) of MAX_LABEL_LEN
arrays of char
. 这声明了
char
的MAX_LABEL_LEN
数组的5元素数组(从初始化程序的数量中获取大小)。 Now you can write to the contents of string_labels[i]
. 现在,您可以写入
string_labels[i]
的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.