如何将 int 和 int* 传递到函数中以定义变量
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));
相关文章:
- 调用'begin(int [n])'没有匹配函数
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 为什么 'main' 函数中的局部 int 变量会自动初始化?
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- swap(int&, int&) 函数不起作用,当交换不使用临时变量时?
- 如何在不返回 C++ 值的情况下退出 int 函数?
- 调用 Parse int 函数时编译 parse 整数程序时出现问题
- 如何将字符串返回到主INT函数
- 为什么要使用int函数而不是void
- int 函数C++可以返回类似 "NULL" 的东西?
- C++int函数.当零是有效的返回值时,我如何检测false
- int const函数(参数)、int函数(const参数)和int函数(parameters)const之间的区别是什
- 类无法从主C++访问 int 函数
- 无法从 int 函数返回结果
- 如何将'int'函数调用到'void'函数
- 强制字符串为int函数以消耗整个字符串
- Int函数参数不能正常工作
- 删除Mat int函数(opencv)
- 为什么float参数适合int函数参数