【问题标题】:Change values of 2D array in function在函数中更改二维数组的值
【发布时间】:2017-12-15 10:42:59
【问题描述】:

如果我把函数内容放到主块中,下面的代码运行得很好,但是函数在这里完全失败了。我目前收到“下标值既不是数组也不是指针也不是向量”错误。我还收到“从不兼容的指针类型”错误中传递“累积”的参数 1 和 4。

void accumulate( double sum[], int ypos[], int xpos[], int vals[], int numvals )
{
    for(int i=0 ; i<numvals ; i++) /// start looping over indices
    {
       sum[ypos[i]][xpos[i]] += vals[i];
    }
}



int main()
{
    int xpos[2]    = {0,1};
    int ypos[2]    = {0,1};
    double vals[2] = {1.01,7};
    int numvals    = 2;
    int size       = 6;
    double sum[size][size];

    for(int i=0; i<size ;i++)
    {
        for(int j=0; j<size ; j++)
            {
            sum[i][j] = 0; // make zeros
            }
    }

    accumulate(sum,ypos,xpos,vals,numvals); // doesn't work

    for(int i=0; i<size ;i++)
    {
        for(int j=0; j<size ; j++)
            {
            printf("%f ", sum[i][j]);
            }
        printf("\n");
    }
}

【问题讨论】:

  • 尝试以下几个修复:1.) 将您的sum 变量放在accumulate() 调用的最后,如下所示accumulate(ypos,xpos,vals,numvals, sum);。 2.) 尝试发送数组的地址,而不是像 accumulate(ypos,xpos,vals,numvals, &amp;sum); 这样的数组副本,它应该对原始数组而不是副本执行更改。 3.) 尝试将accumulate 函数的声明写为void accumulate( ..., double sum[][]);
  • 3) double sum[][] 不起作用,但 double sum[][xsize] 起作用。 2)谢谢!但这会导致警告:“从不兼容的指针类型传递 'accumulate' 的参数 6。还有注释“注意:预期的 'double ()[(sizetype)(xsize)]' 但参数的类型是 'double ()[(sizetype)(ysize)][(sizetype)(xsize)]'" 不知道如何补救。顺便说一句,我是新来的,我不知道如何突出显示代码位。
  • 当您单击添加评论时,会打开一个黄色框,其中包含有关如何突出显示代码的说明。至于主要问题,谷歌搜索:how to send 2D array to a function by reference in c。我已经有一段时间没有编程了c,所以我目前不太流利。

标签: c arrays function pass-by-reference


【解决方案1】:

二维数组在传递给衰减为T (*)[COLS] 的函数时。或者你也可以写

void func( int col, int arr[][col]);

所以你会写

void accumulate( double sum[][size], int ypos[], int xpos[], int vals[], int numvals )
{
    ...
}

您还应该注意ypos[i]xpos[i] 应该在数组size 的范围内,这样您就不会遇到未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-22
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2015-09-22
    相关资源
    最近更新 更多