char array vs. char pointer in C

12 views Asked by At

I used to think it is equivalent to declare a char pointer as char* s or char s[]. It turns out they are not equivalent.

Suppose I have a file a.c:

#include <stdio.h>
extern char s[];

int main() {
    printf("%s\n", s);
    return 0;
}

and another file b.c:

char s[10] = "Hello";

I can compile and link these two files by "gcc a.c b.c". Running the program gets the expected result "Hello".

However, if in "a.c" I declare the variable s as extern char* s, the program can be compiled without any error or warning, but running the program results in a "Segmentation fault". I used to think an array name, when it is being used without brackets, is equivalent to a pointer. Then, what causes the above run-time error?

In a.c, I tried to declare s in two different ways:

  1. extern char s[];
  2. extern char* s; I expect these two ways should be equivalent, but the former succeeds while the latter has run-time error. I saw in Why this simple program in C crashes (array VS pointer) people said char s[] and char* s are two different types. My main question is, inside the same program, these types seem to be interchangeable. Why will it fail with extern variables?
0

There are 0 answers