Can two pointer variables point to the same memory Address?

≯℡__Kan透↙ 提交于 2020-12-30 08:26:09

问题


If p and temp are two pointer variables where p contains NULL and temp points to some memory address.

Now suppose p = temp;

That means now p points to same address as where temp is pointing.

Does that mean two pointer variables p and temp are now pointing to the same memory address?


回答1:


Yes, two pointer variables can point to the same object:

Pointers are variables whose value is the address of a C object, or the null pointer.

  • multiple pointers can point to the same object:

    char *p, *q;
    p = q = "a";
    
  • a pointer can even point to itself:

    void *p;
    p = &p;
    
  • here is another example with a doubly linked circular list with a single element: the next and prev links both point to the same location, the structure itself:

    struct dlist {
        struct dlist *prev, *next;
        int value;
    } list = { &list, &list, 0 };
    



回答2:


Yes it does! Multiple pointers can point to the same thing.




回答3:


Yes two pointer variable can point to the same memory address.

As we know that pointer is a variable which contains address of same data type. Consider the following example in C

#include<stdio.h>

int main() {
int a,*pointer1;
a = 10;
pointer1 = &a;   
int *pointer2;

printf("\n Val : %d",*pointer1);    //This contains address of the variable a - so accessing it with * prints its value - value of “a"
printf("\n Val : %d", *pointer2);   //This contains some junk value - so accessing it with * causes segmentation fault - since there might not be memory address with that junk value       

pointer2 = pointer1;                //Now pointer1 reference i.e.; address value stored in pointer1 is made a copy and now both pointer1 and pointer2 will point to the same memory location
printf("\n Val : %d", *pointer2);   //Now this would print the value of “a"

return -1;
}

The same applies to linked list address. Your variable “p” and “temp” would point to the same memory address now !



来源:https://stackoverflow.com/questions/40959416/can-two-pointer-variables-point-to-the-same-memory-address

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