简体   繁体   English

在某些情况下,带有数组输入的自定义函数打印错误结果?

[英]Custom Function with array input printing wrong result in certain cases?

I needed to make a function that takes an array as input (and its dimensions X,Y or ROW,COL) 我需要制作一个将数组作为输入的函数(其尺寸为X,Y或ROW,COL)
and calculates the sum of all lines (storing each sum in a cell of the new array. 并计算所有行的总和(将每个总和存储在new数组的单元格中。
For an input of NxN array seems to be working perfectly. 对于NxN数组的输入似乎运行良好。
For an input of KxN array where K>N seems to be working perfectly. 对于KxN数组的输入,其中K> N似乎运行良好。

int* linesum(int *ar,int X,int Y)
{
    int i,j,lsum=0;
    int *new=malloc(X*sizeof(int));
    for(i=0;i<X;i++){
        for(j=0;j<Y;j++){
           lsum+=*(ar+i*X+j);
        }
        *(new+i)=lsum;
         lsum=0;
     }
     return new;
}
lsum+=*(ar+i*X+j);

should be 应该

lsum += *(ar+i*Y+j);

or 要么

lsum += *(ar+i+j*X);

The difference between these two is the chosen memory layout. 两者之间的区别在于所选的内存布局。 i counts the current row, while j counts the current column. i计算当前行,而j计算当前列。 There are now two possible (simple) memory layouts for the matrix (assume X=3 and Y=4 as an example): 现在,矩阵有两种可能的(简单的)内存布局(以X=3Y=4为例):

0 1  2  3
4 5  6  7
8 9 10 11

or 要么

0 3 6  9 
1 4 7 10
2 5 8 11

where numbers are the indexes of the linear array storing the matrix elements. 其中数字是存储矩阵元素的线性数组的索引。 In the first case you get the the next element of a given row by simply adding 1 , but you need to jump 4 (the number of columns Y ) to get to the next row. 在第一种情况下,您只需添加1即可得到给定行的下一个元素,但您需要跳4 (列数Y )才能到达下一行。

In the second case you need to jump X=3 (the number of rows) to get to the next element in a given row, but if you want to get to the next row, you simply have to add 1 . 在第二种情况下,您需要跳过X=3 (行数)才能到达给定行中的下一个元素,但是如果要到达下一行,则只需添加1

These two layouts give you the two different pointer arithmetics shown above. 这两种布局为您提供了上面显示的两种不同的指针算法。 You decided the layout when you initialized your array, which you haven't posted, so I cannot know which one is correct in your case. 您在初始化数组时决定了布局,但尚未发布,因此我不知道哪种情况正确。

Note that from a performance viewpoint (if your matrix is very large) the first case is better for your particular access pattern, because the array can be read element by element, while the second layout would require repeatedly jumping Y elements in memory. 请注意,从性能的角度(如果矩阵很大),第一种情况更适合于特定的访问模式,因为可以逐元素读取数组,而第二种布局则需要在内存中重复跳转Y元素。

You could also use double arrays / pointers to get around such pointer arithmetic. 您也可以使用双数组/指针来绕过此类指针算法。 Also I guess it would be good to avoid new as a variable name, even if this is C. If somebody would try to compile your code with a C++ compiler it would throw errors, because new is a reserved keyword there. 同样,我想最好避免使用new作为变量名,即使它是C。如果有人尝试使用C ++编译器编译您的代码,则会抛出错误,因为new是那里的保留关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM