如何将 int 和 int* 传递到函数中以定义变量

How to pass int and int* into function to define variable

本文关键字:int 函数 定义 变量      更新时间:2023-10-16

我有一个 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));