c++ 如何给一个作为函数参数的空指针赋值?

3qpi33ja  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(326)

当我试图赋值给一个NULL指针时,我得到了分段错误。

#include <iostream>
using namespace std;

struct test {
    int val;
};

void insert(test* t, int value) {
    test* x = (test*)malloc(sizeof(test*));
    x->val = value;
    t = x;
}

int main() {
    test* a = NULL;
    insert(a, 5);
    cout << (a->val) << endl;
}

我期待它会打印5,但是它没有。我需要给一个给定的指针赋值,在一个函数里面,我该怎么做呢?

qeeaahzv

qeeaahzv1#

这是一个错误:

test* x = (test*)malloc(sizeof(test*));

应为:

test* x = (test*)malloc(sizeof(test));

现在回到原点,让我们返回新分配的指针:

test* insert(int value) {
    test* x = (test*)malloc(sizeof(test));
    x->val = value;
    return x;
}

int main() {
    test* a = insert(5);
    cout << (a->val) << endl;

    // and let's free "a" while we can
    free(a);
}
qvsjd97n

qvsjd97n2#

指针和其他东西没有什么不同:当用作函数参数时,它们按值传递。
因此main()中的insert(a,5)a的副本传递给函数,然后函数中参数的更改对调用者不可见。
因此,当控制返回到main()时,值a没有改变,它仍然是空指针,并且对a->val求值会产生未定义的行为。
以按引用修复任一传递。

void insert(test *&t, int value)     // note the & here
{
    test* x = (test*)malloc(sizeof(*x));
    x->val = value;
    t = x;
}

int main()
{
    test* a = NULL;
    insert(a, 5);
    cout << (a->val) << endl;
}

注意,我已经更正了传递给malloc()的参数,因为你弄错了。你传递了sizeof(test *),实际上需要将其作为sizeof(test)传递。我使用了传递sizeof(*x)的技术,因为即使(比如)你将指针的类型改为其他类型,它也能工作。
或将指针传递给指针(test **

void insert(test **t, int value)     // note the additional * here
{
    test* x = (test*)malloc(sizeof(*x));
    x->val = value;
    *t = x;                          // note the additional * here
}

int main()
{
    test* a = NULL;
    insert(&a, 5);                   // also note the & here
    cout << (a->val) << endl;
}

在上面的两个选项中,通过引用(而不是指针)传递在C中通常被认为是更可取的。将指针传递给指针在C中很常见,在C中(大多数情况下)不鼓励。
更一般地说,在C++中通常最好使用运算符new,而完全避免使用malloc()。除此之外,它还消除了sizeof的操作数出错的可能性(您已经演示过)。

test* x = (test*)malloc(sizeof(*x));

test* x = new test;

相关问题