更改C中字符串数组中字符的值

时间:2013-05-16 21:50:34

标签: c arrays pointers

我想弄清楚如何使用下面程序中的指针将字母“j”更改为“Y”:

#include <stdio.h>
#include <string.h>

int main()
{

    char *buffer[] = {"ABCDEFGH", "ijklmnop", "QRSTUVWX"};

    printf("the value as %%s of buffer[0] is %s\n", buffer[0]);
    printf("the value as %%s of buffer[1] is %s\n", buffer[1]);
    printf("the value as %%s of buffer[2] is %s\n", buffer[2]);
    printf("the sizeof(buffer[2]) is %d\n", sizeof(buffer[2]));


    printf("the value as %%c of buffer[1][3] is %c\n", buffer[1][3]);
    printf("the value as %%c of buffer[2][3] is %c\n", buffer[2][3]);

    /*create a pointer to the pointer at buffer[1]*/
    char *second = buffer[1];

    /*change character at position 2 of bufffer[1] to a Y*/
    second++;
    second = "Y";

    printf("character at location in second is %c\n", *second);
    printf("character at location in second+2 is %c\n", second+2);

    printf("the values as %%c of second second+1 second+2 second+3 are %c %c %c %c\n",*(second),*(second+1),*(second+2),*(second+3));

    return(0);

}

如何更改位于字符串数组中的字符?

3 个答案:

答案 0 :(得分:2)

尝试写入字符串文字是未定义的行为。

变化:

char *buffer[] = {"ABCDEFGH", "ijklmnop", "QRSTUVWX"};

为:

char buffer[][10] = {"ABCDEFGH", "ijklmnop", "QRSTUVWX"};

答案 1 :(得分:2)

我注意到了一件事

char *second = buffer[1];

/*change character at position 2 of bufffer[1] to a Y*/
second++;
second = "Y";

您尝试设置字符串"Y"而不是字符'Y'

我会做更像

的事情
*second = 'Y';

答案 2 :(得分:1)

有两件事会使这不起作用:

首先,让我们来看看你如何修改:

second++;
second = "Y";

想想你在这里做了什么:你正在使second指向字符串"Y"。这当然不是你的意图。你想要改变任何字符串second指向的第二个字符......有两种方法可以解决这个问题:

/* make the second character of whatever string the variable second to into a 'Y' */
second++;
*second = 'Y';

或者,您可以使用更直观的方法:

second[1] = 'Y';

现在,即使使用此修复程序,您的代码也会尝试修改字符串文字,这将导致未定义的行为。考虑一下你的代码:

char *buffer[] = {"ABCDEFGH", "ijklmnop", "QRSTUVWX"};

此时,buffer[0]buffer[1]buffer[2]指向内存(可能)为只读。实际上是否真的是无关紧要的;你当然应该 TREAT 它是只读的。因此,改变任何东西的尝试都会失败。为了避免这个问题,稍微改变一下:

char *buffer[3];

buffer[0] = strdup("ABCDEFGH");
buffer[1] = strdup("ijklmnop");
buffer[2] = strdup("QRSTUVWX");

毋庸置疑,但是当你完成它们时,请务必致电free以释放buffer[0]buffer[1]buffer[2]指向的字符串!