0

我有以下功能。

char* readFile(const char *fileName){
   std::ifstream file(fileName);
   char *str[50];
   int count=0;
   if(file){
      str[0] = new char[50];
      while(file.getline(str[count], 50)){
         count++;
         str[count] = new char[50];
      }
   }
   return str;
}

前一个函数的行为是:

  • 逐行读取文本文件的内容。
  • 将每一行保存在二维数组的项目中。
  • 然后返回动态二维数组。

现在,我想将从函数返回的二维数组分配给一个合适的变量,或者我想返回对该动态二维数组的引用?

4

3 回答 3

1

不要那样做!!!

您不能在子例程中分配一个数组...或数组数组...,然后像那样将其返回给调用者。

建议:

1) 在 CALLER 中声明“char *str[50]”(不在子程序内)并将其传入

... 或者 ...

2)调用者内部的“新”。“新”从堆中分配;省略它从堆栈中分配。

3) 使用 std::vector<> 而不是简单的数组

恕我直言...

于 2013-07-29T16:49:35.547 回答
0

尽管人们已经向您提出了建议/警告,但您的函数标题应该是char **readFile(const char *fileName).

为了避免堆内存损坏,您应该按如下方式声明该指针数组:

char **str;
str = new char*[50];
于 2013-07-29T16:55:12.093 回答
0

你可以这样做

int** createMatrix(int row , int column)
{
    int **tem = new int*[row];
    for (int i=0; i<row; i++)
    {
        tem[i] = new int [column];
    }

    for(int i=0;i<row;i++)
    {
        for(int j=0;j<column;j++)
        {
            tem[i][j] = 1;
        }
    }
    return tem;
}

int main()
{
    int row=5;int column=1;
   int **arr=createMatrix(row,column);

   for(int i=0;i<row;i++){
    for(int j=0;j<column;j++){
    cout<<arr[i][j];
    }
    cout<<endl;
   }
}
于 2015-05-20T08:19:10.430 回答