如何返回二维字符数组C ++? [英] how to return two dimensional char array c++?

查看:166
本文介绍了如何返回二维字符数组C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个函数内部二维数组,我想回到该数组,和地方把它传递给其他的功能。

i ve created two dimensional array inside a function, i want to return that array, and pass it somewhere to other function..

char *createBoard( ){  
  char board[16][10];
  int j =0;int i = 0;
  for(i=0; i<16;i++){
    	for( j=0;j<10;j++){   
                board[i][j]=(char)201;
    	}	
  }
  return board;
}

但这种不断给​​我的错误

but this keeps giving me error

推荐答案

呀看到你在做什么有返回一个指向一个对象(称为数组)将其在栈上创建的。当它超出范围的阵列被破坏使指针不再指向任何有效的对象(悬摆指针)。

Yeah see what you are doing there is returning a pointer to a object (the array called board) which was created on the stack. The array is destroyed when it goes out of scope so the pointer is no longer pointing to any valid object (a dangling pointer).

您需要确保该数组在堆上分配,而不是使用。成圣的方法来创建现代C ++动态分配的数组是使用类似的std ::矢量类,虽然这更复杂在这里,因为你正在试图建立一个2D数组。

You need to make sure that the array is allocated on the heap instead, using new. The sanctified method to create a dynamically allocated array in modern C++ is to use something like the std::vector class, although that's more complicated here since you are trying to create a 2D array.

char **createBoard()
{
    char **board=new char*[16];
    for (int i=0; i<16; i++)
    {
       board[i] = new char[10];
       for (int j=0; j<10; j++)
         board[i][j]=(char)201;
    }

    return board;
}

void freeBoard(char **board)
{
    for (int i=0; i<16; i++)
      delete [] board[i];
    delete [] board;
}

这篇关于如何返回二维字符数组C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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