-1

I am learning C and I am having some troubles to truly understand arrays and pointers in C, after a lot of research (reading the K&R book (still reading it), reading some articles and some answers here on SO) and taking tons of notes along the way, I've decided to make a little test / program to prove my understanding and to clear some doubts, but I'm yet confused by the warning I am getting using this code:

#include <stdio.h>

int main(int argc, char **argv) {
    char a[3] = {1, 2, 3};
    char *p   = &a;

    printf("%p\n", a);       /* Memory address of the first element of the array */
    printf("%p\n", &a);      /* Memory address of the first element of the array */
    printf("%d\n", *a);      /* 1 */
}

Output compiling with GNU GCC v4.8.3:

warning: initialization from incompatible pointer type                                                                                   
char *p   = &a;                                                                                                                                     
            ^                                                                                                                                                                                                                                                                              
0x7fffe526d090                                                                                                                                        
0x7fffe526d090                                                                                                                                        
1

Output compiling with VC++:

warning C4047: 'initializing' : 'char *' differs in levels of indirection from 'char (*)[3]'

00000000002EFBE0
00000000002EFBE0
1

Why am I getting this warning if &a and a are supposed to have the same value and compiling without warnings when using just a as an initializer for p?

2 Answers2

1

&a is the memory address of the entire array. It has the same value as the address of the first element (since the whole array starts with the first element), but its type is a "pointer to array" and not "pointer to element". Hence the warning.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
1

You are trying to initialize a char* with a pointer to a char[3], which means a char(*)[3].

Unsurprisingly, the compiler complains about the mismatch.

What you wanted to do is take advantage of array-decay (an array-name decays in most contexts to a pointer to its first element):

char* p = a;

As an aside, %p is only for void*, though that mismatch, despite being officially Undefined Behavior, is probably harmless.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118