更改字符指针数组中的内容

时间:2010-11-11 14:56:54

标签: c

这看起来应该很容易,但我花了太多时间。希望有人可以提供帮助。

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

}

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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");
}

答案 2 :(得分:0)

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

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

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

答案 3 :(得分: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"};

这声明了MAX_LABEL_LEN char数组的5元素数组(大小取自初始值设定项的数量)。现在您可以写入string_labels[i]的内容。