2010-11-11 45 views
1

这看起来应该很简单,但我花了太多时间。希望有人能帮助。更改字符指针数组中的内容

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 

} 
+0

你不能 - 他们是常量。 – 2010-11-11 14:59:20

+0

所以这个声明和const char * string_labels = {“one”,“two”,“three”,“four”,“five”}一样。 ?我想如果它没有被声明为const,它将会改变吗?你能解释为什么吗?感谢您的帮助 – 2010-11-11 15:02:42

+0

是的,字符串文字是有效的const,即使它们没有被声明为这样。通常它们驻留在只读段中。 – 2010-11-11 15:06:57

回答

4

它崩溃,因为它在只读内存中。尝试

char string_labels[][6] = { "one", "two", "three", "four", "five" }; 
sprintf(string_labels[0], "xxx"); 
2

要做到这一点,你需要使用一个字符数组,所以你确实有一些运行时可写空间修改:

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"); 
} 
0

string_labels是char指针指向字符串数组文字。由于字符串文字是只读的,因此任何修改它们的尝试都会导致未定义的行为。

您可以更改的string_labels如下的声明,使您的工作sprintf

char string_labels[][6] = { "one", "two", "three", "four", "five" }; 
0

每个string_labels[i]的指向字符串文字,并试图修改未定义行为一个字符串所调用的内容。

您需要声明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"}; 

声明一个5个元素的数组(尺寸从数量取初始化器)MAX_LABEL_LEN阵列char。现在您可以写入string_labels[i]的内容。