gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:08 25 4
gpt4 key购买 nike

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

}

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

最佳答案

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

改变:

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

到:

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

关于改变C中字符串数组中字符的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16598077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com