在函数返回中将数组转换为指针 [英] Cast an array to pointer in function return

查看:163
本文介绍了在函数返回中将数组转换为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中遇到指针问题。代码是:

  int * initArray(){
int a [2]

a [0] = 1;
a [1] = 2;
return a;
}


int main(){
int * b = initArray();

cout<< b<< ---<< *(b)<< endl;
cout<< b + 1 < ---<< *(b + 1)<< endl;
}

输出为

  0021FC20 --- 1 
0021FC24 --- 1431629120


$ b b

您可以看到值错误。



当我尝试将 init 数组代码放入main函数时,它会正确运行。



你能告诉我的代码有什么错误吗?

解决方案

code> initArray 返回在函数返回后不再存在的局部数组的地址。这是一个未定义的行为。



要使变量 a 持久化,即使函数返回,您可以: / p>


  • 声明为 static

  • make

  • 动态分配


I get a problem about pointer in C++. The code is:

int * initArray() {
    int a [2];

    a[0] = 1;
    a[1] = 2;
    return a;
}


int main () {
    int * b = initArray();

    cout << b << "---" << *(b) << endl;
    cout << b + 1<< "---" << *(b + 1) << endl;
}

The output is

0021FC20---1
0021FC24---1431629120

You can see that the value is wrong.

When I try to put the init array code into main function, it runs correctly.

Could you tell what wrong in my code?

解决方案

initArray is returning the address of local array which ceases to exist after the function returns. This is an undefined behaviour.

To make the variable a persistent even when the function returns you can either:

  • declare it as static
  • make it global
  • dynamically allocate it

这篇关于在函数返回中将数组转换为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆