Just a little more info/clarification:
Originally Posted by
sed_y
1) if i declare something like
it creates pointer variable, which is not pointing to a variable yet, but would point to integer variable. so, if i access &p, is it a valid address or junk?
If you're trying to "access" what p points to, then you want *p. Since p is uninitialized, you may find junk or you may crash your application by accessing memory you don't own. Technically, it's undefined behavior, which means anything or nothing is allowed to happen. It's bad juju, so don't do it.
2) when i declare a void pointer like
p1 then holds address of another variable, whose type is not known. Is this address
a valid one ? if so, does it mean that is points to a variable that could be 1 byte, 2 byte etc depending upon the the type?
A void * can point to anything, but the compiler can never be sure of the type of thing it points to. To extend MK27's example:
Code:
char str[256];
p1 = str; // p1 points to 256 byte char block
int x;
p1 = &x; // p1 points to an int
int y = *p1 + 3; // The compiler doesn't know how to dereference a void * (i.e., it can't be sure of what's there)
y = *((int *) p1) + 3; // This works, because you forced the compiler (by casting) to treat p1 as a pointer to an int, thus *p1 refers to an int
Note that casting will keep the compiler from producing warnings. This is fine if you're 100% sure of what you're doing, but if you mis-cast something, you can wreak havoc in your program's memory space. Use sparingly and be careful.