Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
msc Avatar asked Dec 18 '22 04:12

msc


2 Answers

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.

like image 147
Jacques de Hooge Avatar answered Jan 12 '23 01:01

Jacques de Hooge


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".

like image 38
alk Avatar answered Jan 12 '23 01:01

alk