0

Possible Duplicate:
How can I access a shadowed global variable in C?

How to access a global pointer within a function, containing another pointer with the same name and type.

Ex:

#include <stdio.h>

char *ptr = "Hello World";

int main(void)
{
//char ptr = 'a';
 char *ptr = "Global is over written";

printf("%s", ptr); //Here i am trying to print the value of global ptr i.e, "Hello World".

return 0;
}
Community
  • 1
  • 1
user1808215
  • 273
  • 1
  • 6
  • 11

3 Answers3

1

Because you are doing %s do %cyou will get ``a'`

Also you should know about instance member hiding It's also called shadowing.

In layman language you can say : At nearer we got the variable ,we will not look for farther

If local and global has same identifier then local will come into picture first

If you want to know more about how to access global variable in local scope

In C++ use :: scope resolution operator

For C visit the link

Community
  • 1
  • 1
Omkant
  • 9,018
  • 8
  • 39
  • 59
0

You can't access the global variable because the local variable shadows the global one, they are both defined in the same scope and have the same name. Change its name if you want to access both. Read more about Variable Shadowing

iabdalkader
  • 17,009
  • 4
  • 47
  • 74
0

You can get global value by this way

#include <stdio.h>

char *ptr = "Hello World";
char *getGlobalPtr()
{
return ptr;
}

int main(void)
{
char ptr = 'a';
printf("%s", getGlobalPtr()); //Here i am trying to print the value of global ptr i.e, "Hello World".

return 0;
}
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222