简体   繁体   English

在C中,如果将双指针分配给值,为什么指针变量为0?

[英]In C if double pointer is assigned to value, why is the pointer variable 0?

int main() 
{
    int var = 10;
    int **ptr;

    **ptr = var;

    printf("%x\n",ptr);
    printf("%d\n",**ptr);

    return 0;
} 

The above code prints: 0 and 10 上面的代码打印:0和10

Why is ptr 0 ? 为什么ptr 0?

How is the code showing **ptr = 10, if ptr is 0 ? 如果ptr为0,代码如何显示** ptr = 10?

I tried printing *ptr. 我尝试打印* ptr。

This gave segmentation fault (since ptr is 0). 这产生了分段错误(因为ptr为0)。

So, again why not throw segmentation fault at **ptr ? 那么,为什么不在** ptr处引发分段错误呢?

Could this be related to compiler ? 可能与编译器有关吗?

PS: I am using https://www.onlinegdb.com/online_c_compiler to run this code. PS:我正在使用https://www.onlinegdb.com/online_c_compiler来运行此代码。

Pointer ptr is not initialized. 指针ptr未初始化。 Your code invokes undefined behaviour because you are dereferencing an uninitialized pointer. 您的代码将调用未定义的行为,因为您要取消引用未初始化的指针。

You assign the pointer to pointer itself, not the the object referenced. 您将指针分配给指针本身,而不是所引用的对象。

int v = 10;

int *ptr = &v;
int **ptrptr = &ptr;

printf("%d\n", **ptrptr);

So, again why not throw segmentation fault at **ptr ? 那么,为什么不在** ptr处引发分段错误呢?

By incident. 通过事件。 This is UB and your pointer has a random value. 这是UB,您的指针具有随机值。 This value points to another location with the random value. 该值指向具有随机值的另一个位置。 Then you dereference that second one. 然后您取消引用第二个。 So if those random values point to the place in the memory allocated to your program it will not segfault. 因此,如果这些随机值指向分配给程序的内存中的位置,则不会进行段错误。 If not it will segfault. 如果没有,它将出现段错误。

Why it is printing 0 and 10 ? 为什么打印010 Because in this case compiler has optimized all the pointer operations out and assumed that not initialized pointers are NULL, just printing the constant values: 因为在这种情况下,编译器已经优化了所有指针操作,并假定未初始化的指针为NULL,所以只需打印常量值即可:

main:
        push    {r4, lr}
        mov     r1, #0
        ldr     r0, .L3
        bl      printf
        mov     r1, #10
        ldr     r0, .L3+4
        bl      printf
        mov     r0, #0
        pop     {r4, pc}
.L3:
        .word   .LC0
        .word   .LC1
.LC0:
        .ascii  "%x\012\000"
.LC1:
        .ascii  "%d\012\000"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM