vendredi 8 mai 2015

weird behaviour when working with double pointers

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

I was expecting :

Vonjour0
Vonjour1
Vonjour2
Vonjour3
Vonjour4

but I get :

Bonjour0
Bonjour1
Bonjour2
Bonjour3
Bonjour4

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 ?

Aucun commentaire:

Enregistrer un commentaire