我有一个int变量和一个int指针变量,我想将它们传递给一个可以将两个变量都设置为等于数字的函数。我的理解是,我只需要更改setint(b, 20);
代码行即可解决此问题
我一直试图在&
变量前添加*
和b
,但是这导致文件无法编译。
void setint(int* ip, int i)
{
*ip = i;
}
int main(int argc, char** argv)
{
int a = -1;
int *b = NULL;
setint(&a, 10);
cout << a << endl;
setint(b, 20);
cout << b << endl;
此代码的结果应输出:
10
20
当前输出为:
10
segment fault
答案 0 :(得分:1)
您的代码执行/尝试/失败的操作(请参阅添加的注释):
int main(int argc, char** argv)
{
int a = -1; // define and init an int variable, fine
int *b = NULL; // define and init a pointer to int, albeit to NULL, ...
// ... not immediatly a problem
setint(&a, 10); // give the address of variable to your function, fine
cout << a << endl; // output, fine
setint(b, 20); // give the NULL pointer to the function,
// which attempts to dereference it, segfault
cout << b << endl;
什么可以实现您的预期(至少可以实现我认为的目标...):
int main(int argc, char** argv)
{
int a = -1;
int *b = &a; // changed to init with address of existing variable
setint(&a, 10);
cout << a << endl;
setint(b, 20); // now gives dereferencable address of existing variable
cout << *b << endl; // output what is pointed to by the non-NULL pointer
顺便说一句,如果之后再次输出a
,它将显示通过指针设置的值,即20,它将覆盖先前写入的值10。
答案 1 :(得分:1)
void setint(int* ip, int i)
{
if(ip != NULL) //< we should check for null to avoid segfault
{
*ip = i;
}
else
{
cout << "!!attempt to set value via NULL pointer!!" << endl;
}
}
int main(int argc, char** argv)
{
int a = -1;
int *b = NULL;
setint(&a, 10);
cout << a << endl;
setint(b, 20); //< should fail (b is currently NULL)
// cout << *b << endl;
b = &a; //< set pointer value to something other than NULL
setint(b, 20); //< should work
cout << *b << endl;
return 0;
}
答案 2 :(得分:0)
您需要使用以下方式为b(编译器已在堆栈上分配a)分配内存:
#include <stdlib.h>
int *b = (int *)malloc(sizeof(int));