PaxPrz
PaxPrz

Reputation: 1928

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!!

Upvotes: 2

Views: 3365

Answers (2)

mtijanic
mtijanic

Reputation: 2902

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

Upvotes: 2

Tom Tsagkatos
Tom Tsagkatos

Reputation: 1494

The error on pointer = &words[0]; happens because you are taking an 'array of pointers' and make it point to the first array of characters, since pointer points to a char this makes no sense. Try something like:

char *pointer[5];
pointer[0] = &words[0][0];
pointer[1] = &words[1][0];
//...

This will make your pointers to point at the first char of your strings (which I assume is the desired behavior?)

Upvotes: 1

Related Questions