gpt4 book ai didi

c - 使用双指针时的奇怪行为

转载 作者:行者123 更新时间:2023-12-03 03:37:41 25 4
gpt4 key购买 nike

我需要帮助来理解为什么在这个小程序中我无法正确操作指针:

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change(char *s[][15]){
int i=0;
while(i<5){
if(s[i][0]=='B') s[i][0]='v';
i++;
}
}
/*My code is supposed to allocate dynamically 5 arrays of 15 chars each
(like tab[5][15])and then put a message on them and try to modify the messages.
In this particular case i'm trying to change the first letter of each string to 'V'.
I'm doing this little experience because of another program
in which i have difficulties accessing double arrays*/
int main(){
int i;
char **s;
s =malloc(5*sizeof(char*));
for(i=0;i<5;i++){
s[i]=malloc(15*sizeof(char));
sprintf(s[i],"Bonjour%d",i);
}
change(s);
for(i=0;i<5;i++){
printf("%s\n",s[i]);
}
return 0;
}

我在期待:

Vonjour0
Vonjour1
Vonjour2
Vonjour3
Vonjour4

但我明白:

Bonjour0
Bonjour1
Bonjour2
Bonjour3
Bonjour4

我正在为另一个程序测试这个小代码,但我不明白为什么数组没有改变。在我的其他程序中,我无法访问双指针或打印内容。所以我的问题是:为什么在这个程序中我无法修改数组的内容?

最佳答案

您的更改方法需要使用“char** s”而不是 char *s[][15]。这是因为您的方法需要一个指向多维数组的指针。因此,这是不可变的,因为字符串的原始数据类型是指向字符串数组的指针(即:字符数组)。

希望这是清楚的。

关于c - 使用双指针时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129048/

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