1

我试图弄清楚如何使用下面程序中的指针将字母“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);

}

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

4

3 回答 3

2

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

改变:

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

至:

char buffer[][10] = {"ABCDEFGH", "ijklmnop", "QRSTUVWX"};
于 2013-05-16T21:54:27.473 回答
2

只是我注意到的一件事

char *second = buffer[1];

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

您正在尝试设置为 string"Y"而不是 char 'Y'

我会做一些更像

*second = 'Y';
于 2013-05-16T21:54:57.767 回答
1

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

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

second++;
second = "Y";

想想你在这里做什么:你正在second指向 string "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]指向(可能)只读的内存。不管它是否真的是无关紧要的;您当然应该其视为只读。因此,改变任何事物的尝试都会失败。为了避免这个问题,稍微改变一下:

char *buffer[3];

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

不用说,但一定要调用free释放 指向的字符串,buffer[0]当你完成它们时!buffer[1]buffer[2]

于 2013-05-16T22:02:20.923 回答