Strange behavior when dealing with double pointers

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

    #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;
    }

      

I expected:

Vonjour0
Vonjour1
Vonjour2
Vonjour3
Vonjour4

      

but i get:

Bonjour0
Bonjour1
Bonjour2
Bonjour3
Bonjour4

      

I am testing this little code for another program and I don’t understand why the arrays are not changing. In my other program, I cannot access the double pointer or print the content. so my question is: why in this program I cannot change the contents of the arrays?

+3


source to share


3 answers


Your change method should use "char ** s" instead of char * s [] [15]. This is because your method expects a pointer to a multidimensional array. This is unchanged in the result, since your original data type for the string is a pointer to an array of strings (IE: character array).



Hope this was clear.

+2


source


It should be



char **change(char **s){
              int i=0;
              while(i<5){
                  if(s[i][0]=='B') s[i][0]='v';
                  i++;
              }
              return s;
          }

      

+1


source


You only need to change the function argument to char *s[]

.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void change(char *s[]){
    int i=0;
    while(i<5){
        if(s[i][0]=='B') s[i][0]='v';
        i++;
    }
}

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;
}

      

Program output:

vonjour0
vonjour1
vonjour2
vonjour3
vonjour4

      

0


source







All Articles