【问题标题】:problem reading 2d array after passing a ponter from one function to another将指针从一个函数传递给另一个函数后读取二维数组的问题
【发布时间】:2020-09-14 19:45:44
【问题描述】:

我正在尝试从我在主函数中声明的二维数组中读取数据,但同时处于不同的函数中。我认为如果我将发送一个指向该数组的第一个单元格的指针,那么这将是可能的,但是我仍然遇到问题

问题是将我在主函数中声明的二维数组传递给另一个函数,该函数本身是从另一个函数调用的。我知道这是一个基本问题,但经过多次尝试,我仍然无法理解我做错了什么,并真诚地感谢您的帮助。

我已将以下代码简化为以下代码中的问题:

void main(){
N = 5, M = 4
double arr[][4] = {
    { 1,2,1,5 },
    { 8,9,7,2 },
    { 8,7,6,1 },
    { 5,4,5,3 },
    { 5,4,5,3 }
};

double(*pointer)[4];   // pointer creation
pointer = arr;         //assignation

function_1(pointer ,N,M);
}

function_1(double *arr, int N, int M){

  function_2(arr,N,M);
}
function_2(double *arr, int N, int M){
  
  int c = 0;
  
  for(int i=0; i<n; i++){
      for(int j=0l j<M; j++){
      arr[i][j] = c;          // error while trying to read from arr[i][j]
      c += 1;
   } 
  }
}

【问题讨论】:

  • 如果您想将类似double(*pointer)[4] 的内容传递给函数,您的函数最好接受类似double(*pointer)[4] 的参数。 double *arr 不能替代它。
  • 这对你有用吗? stackoverflow.com/a/35657313/1563833
  • 非常感谢。我会阅读参考资料并尝试您建议的解决方案,以找到最“优雅”的方法。

标签: arrays c pointers


【解决方案1】:

我在所有函数中都指定了数组的长度

function_2(double arr[5][4], int N, int M)
{
    int c = 0;
    for(int i=0; i<N; i++)
    {
        for(int j=0; j<M; j++)
        {
            arr[0][0] = c;
            c += 1;
        } 
    }
}

void function_1(double arr[5][4], int N, int M)
{
    function_2(arr,N,M);
}

int main()
{
    int N = 5, M = 4;
    double arr[][4] = 
    {
        { 1,2,1,5 },
        { 8,9,7,2 },
        { 8,7,6,1 },
        { 5,4,5,3 },
        { 5,4,5,3 }
    };
    function_1(arr ,N,M);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多