Reputation: 34588
In the following code, a pointer points to its own memory address.
#include <stdio.h>
int main()
{
void * ptr;
ptr = &ptr;
return 0;
}
Would it make sense, if the pointer was able to point to its own memory address?
Upvotes: 3
Views: 871
Reputation: 1090
Another aspect that has not been mentioned yet, is that it goes against strict typing.
If ptr
is of type void *
, then &ptr
is of type void **
and should not be assigned to ptr
due to the type mismatch (void *
vs. void **
).
However C and C++ are generally very lax when it comes to pointer types, whenever one assigns to a void *
, because a void *
is supposed to be able to point to just about anything.
But suppose you actually want to dereference ptr
properly, you would (after your assignment) have to do it like
*(void **)ptr = ...
assuming you actually want to dereference it at some point.
Upvotes: -3
Reputation: 6990
No, it doesn't make sense. If you can find variable ptr, you can just do &ptr. It will give you the same results as the contents of ptr.
Moreover since ptr only tells something about itself, it's useless anyhow. It doesn't provide any info meaningful to the rest of your program.
Come to think of it, there's one exception. You could use the case where ptr == &ptr as a kind of special value, like NULL. So, in that case I would consider it useful.
The fun of it is that in that case the value &ptr makes sense as a special value precisely while it doesn't make sense as the address of something, just like NULL.
Upvotes: 7
Reputation: 70901
Pointer point to its own memory address
It's legal.
Whether it "makes sense" 100%ly depends on the context and though "is primarily option based".
Upvotes: 5
Reputation: 67476
It makes sense as it is legal C language assignment. Another question is what for. IMO this is just the scholastic consideration without any practical use.
Upvotes: 2