Can pointer point to itself memory address in C?

牧云@^-^@ 提交于 2019-12-07 10:58:14

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/45769003/can-pointer-point-to-itself-memory-address-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!