8

I have the following code:

char *array1[3] = 
{
    "hello",
    "world",
    "there."
};

struct locator_t
{
    char **t;
    int len;
} locator[2] =
{
    {
        array1,
        10
    }
};

It compiles OK with "gcc -Wall -ansi -pedantic". But with another toolchain (Rowley), it complains about

warning: initialization from incompatible pointer type

on the line where char **t is. Is this indeed illegal code or is it OK?

Thanks for all the answer. I now know where my problem was. However, it raises a new question:

string array initialisation

Community
  • 1
  • 1
lang2
  • 11,433
  • 18
  • 83
  • 133

4 Answers4

4

Seems perfectly legal to me; char *[3] decays to char **, so the assignment should be valid.

Neither GCC 4.4.5 nor CLang 1.1 complains.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

Although in practice array1 should decay to a pointer of type char **, its real type is in fact char *[3], hence the warning.

To suppress the warning, you could try casting it explicitly:

...
(char **) array1;
...
Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
1

array1 is (char *)[3], which is semantically different from char **, although in the assignment it should be gracefully degraded to a char **

Nico
  • 1,328
  • 8
  • 7
-1

Pointers and arrays and only compatible in static scope. In global scope a pointer and an array are not the same, mixing the two will result in undefined behavior. So in my opinion, the warning is correct.

Try putting:

extern char *array1[3] = 
{
    "hello",
    "world",
    "there."
};

in one module and:

extern char **array1;

struct locator_t
{
    char **t;
    int len;
} locator[2] =
{
    {
        array1,
        10
    }
};

in another, compile and link. (I haven't tried it…) I would expect things to go wrong...

Henry Rusted
  • 379
  • 6
  • 15
  • Your first module doesn't compile because you can't declare a variable `extern` and initialize it in one statement. If you fix that, you might get linker errors because the declared types don't match. – Fred Foo Oct 20 '11 at 11:21
  • Funny, my first module compiles with warnings but the seconds doesn't for the same reason as original question… That was a quick flash that went wrong, I wanted to underline the difference between arrays and pointers in global scope. – Henry Rusted Oct 20 '11 at 16:03