user2863147
user2863147

Reputation: 23

Same address space on C

I have an issue that some of you can help me out

I currently have this code (these are both global variables)

    int * x;
    int * y;

Now, on the main method I want to get the address space of those two, as follows

    int main ( int argc, char *argv[ ] ){
     printf("%p\n",x);
     printf("%p\n",y);
     system("pause");
     return 0;
     }

In both cases I get 00000000 as the address space (as if they "shared" the same address space) My questions are 1) Why does it gets the address space of 0? It is supposed to take another address since we are talking about global variables 2) Why does both of the variables are sharing the same space in memory when they should take 000000 and 000004 (assuming that the assignment is correct)

Thanks in advance for your answers

Upvotes: 0

Views: 127

Answers (3)

attaboy182
attaboy182

Reputation: 2079

1.) They are both uninitialized pointers. The compiler automatically initializes global pointers to NULL (address is 0)

2.) They are not sharing the same address. They are both pointing to NULL (address is 0)

Hope this helps.

Upvotes: 0

microarm15
microarm15

Reputation: 171

Because uninitialized global variables/pointers are automatically initialized to zero/NULL.

Upvotes: 0

Guntram Blohm
Guntram Blohm

Reputation: 9819

You're printing the values of the pointers, the address they are pointing to. This is 0 in both cases as global variables get initialized to 0.

If you want to know the addresses of the pointer variables, use

int main ( int argc, char *argv[ ] ){
 printf("%p\n",&x);
 printf("%p\n",&y);
 system("pause");
 return 0;
}

Upvotes: 5

Related Questions