Why this simple program in C crashes (array VS pointer)

Viewed 405

I have two files:

In file 1.c I have the following array:

char p[] = "abcdefg";

In file 0.c I have the following code:

#include <stdio.h>

extern char *p; /* declared as 'char p[] = "abcdefg";' in 1.c file */

int main()
{
    printf("%c\n", p[3]);   /* crash */
    return 0;
}

And this is the command line:

gcc  -Wall -Wextra     0.c  1.c

I know that extern char *p should've been: extern char p[];, but I just want an explanation of why it doesn't work in this particular case. While it works here:

int main()
{
    char a[] = "abcdefg";
    char *p = a;

    printf("%c\n", p[3]);   /* d */
    return 0;
}
3 Answers
Related