向函数传递指针不会返回值

Passing pointers to function does not return value

本文关键字:返回值 指针 函数      更新时间:2023-10-16

在以下情况下,我得到NumRecPrinted=0,即num是0

int main()
{
    int demo(int *NumRecPrinted);
    int num = 0;
    demo(&num);
    cout << "NumRecPrinted=" << num;    <<<< Prints 0
    return 0;
}
int demo (int *NumRecPrinted)
{
    int no_of_records = 11;
    NumRecPrinted = &no_of_records;
}

您将地址分配给指针,而不是将值分配给所指向的。像这样试试

int demo (int *NumRecPrinted)
{
     int no_of_records = 11;
     *NumRecPrinted = no_of_records; 
} 

否!

*NumRecPrinted = no_of_records;

请参阅"*"表示"的值","&"表示"地址"。您想要更改NumRecPrinted的"值",这就是为什么上面的工作原理。您所做的是将num_of_records的"地址"提供给NumRecPrinted。

您所做的只是将本地指针指向demo函数内的一个新整数处的intNumRecPrinted

您要更改它指向的整数,而不是更改它指向哪里。

*NumRecPrinted = no_of_records;

您可以在您的版本中看到,您正在获取一个局部变量的地址,并且您知道它不是您关心的变量的地址而是它的值。

正如其他人所指出的,*=和&=的值的地址。所以你只是给方法中的指针分配了一个新地址。您应该:

*NumRecPrinted = no_of_records; 

请参阅这篇关于指针的优秀教程。例如:

  int firstvalue = 5, secondvalue = 15;
  int * p1, * p2;
  p1 = &firstvalue;  // p1 = address of firstvalue
  p2 = &secondvalue; // p2 = address of secondvalue
  *p1 = 10;          // value pointed by p1 = 10
  *p2 = *p1;         // value pointed by p2 = value pointed by p1
  p1 = p2;           // p1 = p2 (value of pointer is copied)
  *p1 = 20;          // value pointed by p1 = 20

您想要*NumRecPrinted=no_of_records;

这意味着,"将NumRecPrinted指向的对象设置为等于no_of_records"。