0

I have a question about the warning "assignment from incompatible pointer type". Why does the following code

const char files[][128]={"file1","file2","file3"};
char **ptr;

ptr=files;

produce this warning? Something more complex is working just fine:

typedef struct
{
double **matrix;
}foo_struct;

void fun(foo_struct *foo)
{
double **ptr;
ptr=(*foo).matrix;
}

So I can't really see why the first one does give this warning, because I thought that something like files[][128] is of the same type as char **ptr. The only difference I see is that C knows about the span/size of the valid memory region, whereas in the second example it doesn't.

Here's something similar, which didn't help me though: Warning about assignment from incompatible pointer type when using pointers and arrays?

Thank you for your help!

Community
  • 1
  • 1
Clemens
  • 313
  • 4
  • 15
  • 1
    Has been asked many times. Possible duplicate of [Is 2d array a double pointer?](http://stackoverflow.com/questions/7586702/is-2d-array-a-double-pointer) – AnT stands with Russia Jun 24 '13 at 14:38

2 Answers2

2

That has to do with the fact that

const char files[][128]={"file1","file2","file3"};

makes files of type const char [][128] which is equivalent to a type const char (*)[128].

In this scenario your data is laid out in blocks of 128 characters per string. Dereferencing files finds you a block of 128 characters.

On the contrast a char ** expects to find an array of char * pointers to char when dereferencing. If you want files to be compatible with char ** you have to declare it as

const char * files[]={"file1","file2","file3"};
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
1

files has type char (*)[128], not char**; there is no second level of pointer (and we're not talking about const yet; it's another can of worms).

This code should not show a warning (except the one for constness)

const char files[][128]={"file1","file2","file3"};
char (*ptr)[128];

ptr=files;
Medinoc
  • 6,577
  • 20
  • 42