当我试图赋值给一个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,但是它没有。我需要给一个给定的指针赋值,在一个函数里面,我该怎么做呢?
2条答案
按热度按时间qeeaahzv1#
这是一个错误:
应为:
现在回到原点,让我们返回新分配的指针:
qvsjd97n2#
指针和其他东西没有什么不同:当用作函数参数时,它们按值传递。
因此
main()
中的insert(a,5)
将a
的副本传递给函数,然后函数中参数的更改对调用者不可见。因此,当控制返回到
main()
时,值a
没有改变,它仍然是空指针,并且对a->val
求值会产生未定义的行为。以按引用修复任一传递。
注意,我已经更正了传递给
malloc()
的参数,因为你弄错了。你传递了sizeof(test *)
,实际上需要将其作为sizeof(test)
传递。我使用了传递sizeof(*x)
的技术,因为即使(比如)你将指针的类型改为其他类型,它也能工作。或将指针传递给指针(
test **
)在上面的两个选项中,通过引用(而不是指针)传递在C中通常被认为是更可取的。将指针传递给指针在C中很常见,在C中(大多数情况下)不鼓励。
更一般地说,在C++中通常最好使用运算符
new
,而完全避免使用malloc()
。除此之外,它还消除了sizeof
的操作数出错的可能性(您已经演示过)。做