Search code examples
carrayspointerspointer-to-pointer

How to assign 2D string array to char pointer array?


I've been trying to assign char words[x][y] to a char* pointer[x]. But compiler is giving me a error

array type 'char *[5]' is not assignable pointer = &words[0]

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

int main(){
    char words[5][10]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
    char *pointer[5];
    pointer = &words[0];
    char **dp;
    dp = &pointer[0];

    int n;
    for(n=0; n<5; n++){
        printf("%s\n", *(dp+n));
    }
return 0;
}

But the code works while

char *pointer[5]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
char **dp;
dp = &pointer[0];

all I need is to correctly assign the 2D array into pointer array!!


Solution

  • Unfortunately, you can't do it the way you want. char words[5][10] doesn't store the pointers themselves anywhere, it is effectively an array of 50 chars. sizeof(words) == 50

    In memory, it looks something like:

    'A','p','p','l','e','\0',x,x,x,x,'B','a'...
    

    There are no addresses here. When you do words[3] that is just (words + 3), or (char *)words + 30

    On the other hand, char *pointer[5] is an array of five pointers, sizeof(pointer) == 5*sizeof(char*).

    So, you need to manually populate your pointer array by calculating the offsets. Something like this:

    for (int i = 0; i < 5; i++) pointer[i] = words[i];