[英]How to pass int and int* into function to define variable
我有一个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
您的代码执行/尝试/失败的操作(请参阅添加的注释):
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先前写入值。
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;
}
您需要使用以下方式为b分配内存(编译器已经在堆栈上分配了a):
#include <stdlib.h>
int *b = (int *)malloc(sizeof(int));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.