簡體   English   中英

更改字符指針數組中的內容

[英]Changing contents in array of character pointers

這似乎很容易,但是我花了太多時間在上面。 希望有人可以提供幫助。

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

}

由於它位於只讀內存中,因此崩潰。 嘗試

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

為此,您需要使用一個字符數組,以便實際上您有一些運行時可寫的空間來進行修改:

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是指向字符串文字的char指針數組。 由於字符串文字是只讀的,因此任何嘗試修改它們的操作都會導致未定義的行為。

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

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

每個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"};

這聲明了charMAX_LABEL_LEN數組的5元素數組(從初始化程序的數量中獲取大小)。 現在,您可以寫入string_labels[i]的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM