msc
msc

Reputation: 34588

Can pointer point to itself memory address in C?

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

Answers (4)

iolo
iolo

Reputation: 1090

Another aspect that has not been mentioned yet, is that it goes against strict typing.
If ptris 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

Jacques de Hooge
Jacques de Hooge

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

alk
alk

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

0___________
0___________

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

Related Questions