使用双指针时的怪异行为

乌鸦K

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

    #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]。这是因为您的方法需要一个指向多维数组的指针。结果,这是不可变的,因为字符串的原始数据类型是指向字符串数组的指针(即:字符数组)。

希望那是清楚的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章