2010-11-11 33 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]的內容。