1

Warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]

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

int main() {
    char *p; 
    char str[100];
    p = &str;

    return 0;
}

What is this incompatible pointer type thing? I'm searching for an hour but couldn't find anything that cover the conceptual part of it. And what am I doing wrong here, that causes this warning?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Left Over
  • 241
  • 3
  • 16

3 Answers3

4

&str of type char (*)[100] which is incompatible with the type char *. What you need is just assign str to p as array decay to pointer to it's first element when used in an expression except when an operand of sizeof and unary & operator.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • I'm quite confused of `char (*)[100] vs char *` Can you suggest me a resource so I can learn about this subject matter. – Left Over Aug 17 '17 at 15:26
  • @LeftOver what is confusing exactly? `char` is not the same as `char[100]`, so pointers to those are not the same either. – n. m. could be an AI Aug 17 '17 at 15:40
  • @LeftOver Reading non-trivial C type specifiers can be confusing for the beginner, especially because they contain no identifier for a variable (or parameter or whatever). Here are some type specifiers and matching variable declarations: `char`: `char x;` (single `char`); `char[100]`: `char x[100];` (array of 100 `char`); `char *`: `char *x;` (pointer to `char`); `char *[100]`: `char *x[100];` (array of 100 pointers to `char`); `char (*)[100]`: `char (*x)[100];` (pointer to array of 100 `char`). – Ian Abbott Aug 17 '17 at 15:51
2

str is typed char[100].

So taking it's address using the &-operator, gives you an address of a char[100], not the address of a char.

The relevance of the difference becomes obvious if you think on how pointer arithmetic works:

Incrementing a pointer by 1 moves its value as many bytes as the type uses the pointer points to. Which is 100 for a pointer to char[100] and just 1 for a pointer to char.


To define a pointer to an array the somewhat unintuitive notation

T (*<name>)[<dimension>]

is used.

So a pointer to char[100] would be

char (*ps)[100];

So one can write:

char str[100];
char (*ps)[100] = &str; // make ps point to str

to have ps point to the array str.

Doing

char * p = str;

makes p point to the 1st element of str, which is a char.

The interesting thing is that p and ps point to the same address. :-)

But if you'd do

ps = ps + 1;

ps got incremented 100 bytes, whereas when doing

p = p + 1;

p got incremented just one byte.

alk
  • 69,737
  • 10
  • 105
  • 255
1

The compiler expects a pointer to char but tried to assign pointer to char[100]. That's not the same :)

See these for more detailed discussion:

C pointers : pointing to an array of fixed size

C: differences between char pointer and array

drake
  • 111
  • 4