简体   繁体   English

函数参数中的整数双指针

[英]Integer double pointer in function parameter

What I've learned so far about pointers is: a pointer refers to the address of a variable 到目前为止,我对指针的了解是:指针指向变量的地址

int a = 0 ;
int *p = &a ;

and a double pointer refers to the address of a pointer variable 并且双指针指向指针变量的地址

int *b = &a ;
int **c = &b ;

and as far as what I know is correct, I should have no problem in executing the codes below: 据我所知正确的,我在执行以下代码时应该没有问题:

#include<stdio.h>

void reference(int **input)
{
    **input = 963;
}

int main(void)
{
    int* value;

    reference(&value);

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

    system("PAUSE");
    return 0;
}

In this code, I expected to see "963" in console. 在这段代码中,我希望在控制台中看到“ 963”。 When I execute the code, build succeeds but cmd just stops. 当我执行代码时,构建成功,但cmd停止。 What could be a possible problem for this simple code? 这个简单的代码可能会出现什么问题?

We can rewrite 我们可以重写

int* value;
reference(&value);

without the function, giving 没有功能,给

int* value;
int **input = &value;
**input = 963;

Because *input is value , the whole thing is equivalent to 因为*inputvalue ,所以整个事情等同于

int* value;
*value = 963;

This is wrong because value is uninitialized. 这是错误的,因为value未初始化。 Dereferencing an uninitialized pointer has undefined behavior. 取消引用未初始化的指针具有未定义的行为。

Fix: 固定:

int x;
int *value = &x;
reference(&value);

Ie make value point somewhere were 963 can be stored. 即,可以在963处存储value点。

The issue is that value is a pointer that doesn't point to anything, it's dangling. 问题在于, value是一个指针,它不指向任何东西,而是悬而未决。 You need to set it first. 您需要先进行设置。

int foo;
int* value;
value = &foo;

And now it works without crashing. 现在,它可以正常工作而不会崩溃。 You need to have a place for your data, either ont he stack (local variables) or on the heap (allocated with malloc ). 您需要在堆栈上(本地变量)或堆上(使用malloc分配)放置数据。

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

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