双指针时怪异的行为 [英] weird behaviour when working with double pointers

查看:144
本文介绍了双指针时怪异的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助理解为什么在这个小程序我不能正确处理指针:

I need help to understand why in this little program i cannot manipulate correctly pointers:

    #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

我测试这个小code另一个程序,我不知道为什么数组不改变。
在我的其他程序无法访问的双指针或打印的内容。
所以我的问题是:为什么在这个节目,我不能修改阵列的含量

I'm testing this little code for another program and I don't get why the arrays don't change. In my other program I can't access the double pointer or print the content. so my question is : why in this program I can't modify the content of the arrays ?

推荐答案

您更改方法需要使用字符** S,而不是字符* S [] [15]。这是因为你的方法需要一个指向多维数组。这是不可改变的结果,因为字符串的原始数据类型是一个指向字符串数组(IE:字符数组)。

Your change method needs to use "char** s" instead of char *s[][15]. This is because your method is expecting a pointer to a multi-dimensional array. This is immutable as a result, since your original data type for the string is a pointer to an array of strings (IE: An array of chars).

希望这是显而易见的。

这篇关于双指针时怪异的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆