Why a globle pointer can't re-point to another object, but a local pointer can?

Viewed 59

I'm new to C especially new to C pointers. The problem here is simple:

#include <stdio.h>

char *p1 = "Hello";
char *p2;
p2 = "world";  // error: redefinition of 'p2' with a different type: 'int' vs 'char *'

int main()
{
   char *p3 = "Hello";
   char *p4;
   p4 = "world";  // OK!  p4 can re-point to somewhere
   
   return  0;
}

I declare a global pointer p2, but I try to assign a string, "hello",to it.
But QT prompt a error: redefinition of 'p2' with a different type: 'int' vs 'char *'

It says p2 is a int? But I clearly declared it a char *;

However, p4, as a local pointer, can do the same thing! All works fine in main function.

What's going on? I'm confusing!

2 Answers

What's going on is you can't run code at global scope. Only static initializers allowed, and they must be compile-time constants.

Works:

char *p2;
int main()
{
    p2 = "world";
}

The error message might not be the most helpful in this case. The only thing that can exist at global scope is a declaration or a definition (with optional initializer), so the compier thinks p2 = "world" is declaring p2 to be a new variable, gives it the implicit type int, and then sees that conflicts with the declaration of p2 immediately above and complains.

Instructions, like assignment in this case, can exist only in functions. Outside of functions you can only declare or define variables, types or other functions.

So when you say p2 = "world"; outside of a function, the compiler assumes through process of elimination that you must be declaring a variable, and since you didn't give it a type, it assumes you mean int. So the code you wrote is equivalent to:

char *p1 = "Hello";
char *p2;
int p2 = "world";  // error: redefinition of 'p2' with a different type: 'int' vs 'char *'

At this point it should be obvious why it's telling you you're redefining p2 as an int.

Related