Corneille K
Corneille K

Reputation: 73

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 ?

Upvotes: 3

Views: 86

Answers (3)

Subinoy
Subinoy

Reputation: 488

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

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34585

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

Upvotes: 0

GEMISIS
GEMISIS

Reputation: 444

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).

Hopefully that was clear.

Upvotes: 2

Related Questions