指针返回类型的函数

纳文

我试图了解函数的指针返回类型。下面的示例产生类型转换错误。

#include <iostream>
using namespace std;

int* abc(int* y)
{
    int x=y;
    int *z = &x;
    x++;
    return z;
}

int main()
{
  int *a = abc(100);
  int b = *a;
  cout << a <<endl;
  cout << b <<endl;
  return 0;
}

错误消息是:

In function 'int* abc(int*)': 6:11: error: invalid conversion from 'int*' to 'int' [-fpermissive]  
In function 'int main()': 14:19: error: invalid conversion from 'int' to 'int*' [-fpermissive] 
4:6: note: initializing argument 1 of 'int* abc(int*)'

如何解决上述错误,以及以下函数形式及其适当的调用语法之间的区别是什么,

  1. int *函数()
  2. int * function()
  3. int * function()
萨胡

中的参数类型

int* abc(int* y)

int*当您调用该函数时,

int *a = abc(100);

你逝去100,一个int它不是指向的指针int

您可以使用以下方法解决此问题:

选项1

更改参数类型。

int* abc(int y) { ... }

选项2

更改调用函数的方式。

int x = 100;
int *a = abc(&x);

如果您遵循此选项,

线

int x=y;

需要修改。键入y就是int*,不是int您必须将行更改为:

int x=*y;

问题

您正在从函数中返回局部变量的地址。在调用函数中取消引用该地址是未定义的行为。

当您从函数返回地址并且调用函数取消引用该地址时,该地址在调用函数中必须有效。一种方法是使用分配堆内存malloc

int* abc(int* y)
{
    int* x = malloc(sizeof(int));
    *x = (*y + 1);
    return x;
}

执行此操作时,您必须记住要调用free调用函数。

int x = 100;
int *a = abc(&x);

// Use a

// Deallocate memory
free(a);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章