Pointer typecasting in Global scope..

Hi i need a small clarification for the below code. could anyone pls help me.

1st case:
A void pointer and a int variable in local scope.

=> works fine.

main()
{

int a = 10;
void *ptr;
ptr = (void *)&a;

printf("%d
",*(int *)ptr);
_getch();

}

2nd case:
A void pointer and a int variable in global scope.

int a = 10;
void *ptr;
/*Error in below line -> 'int' differs in levels of indirection from 'void *' */
ptr = (void *)&a;

main()
{

//printf("%d
",*(int *)ptr);
_getch();

}

Could u pls tell me the reason, why am getting an error when doing pointer typecasting in a global scope.

Compiler used : Visual studio 2005

Comments

  • [color=Blue]1. Try not to do it in separate line:
    2. You also do not need a cast if pointer is void*.[/color]
    [code]
    int a=10;
    void* p = &a;
    [/code]
    [color=Blue]Separate line of code like this does not belong to any function, on the other hand - the initializer on the same line is OK to do.[/color]
  • Hi Dude,

    Thanks for ur kind reply...

    My concern is, the two lines of code may not belongs to any function. In the other hand, it will be treated as global variable and global pointer to that particular file. In this case why i should get error.

    What could be the reason...


  • [color=Blue]I sincerely do not know... I can guess that separate line of code belongs to code section and initialization on the same line belongs to a data section. I am thinking C/C++ standard has some rules for such situation.

    I never read the standard anyhow - in case of a compiler giving me errors - I usually rearrange the code until compiler stops the error.

    :-)[/color]
  • Thanks Dude !!!
    I will post the answer if i come to know the answer u too do the same...
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories