c - 在 C 中通过引用传递动态长度的二维结构数组

标签 c function dynamic struct multidimensional-array

  1. 我收到如下警告:“从不兼容的指针类型传递 'arraySumLoc' 的参数 1”
  2. 通过函数arraySumLoc()得到的结果不正确,无法找出原因。
  3. 如果我想在数组声明期间使用 maloc(),需要进行哪些修改。
<小时/>
#include<stdio.h>
#include<conio.h>

typedef struct item {
    double cost;
    double commission;
} item;

typedef struct loc {
    int x;
    int y;
} loc;

double arraySumLoc(struct item *arr, loc fromLoc, loc toLoc) {

    double sumOfCost = 0.0;
    int fromX, fromY, toX, toY, indexX, indexY;

    if (fromLoc.x > toLoc.x) {
        fromX = toLoc.x;
        toX = fromLoc.x;
    } else {
        fromX = fromLoc.x;
        toX = toLoc.x;
    }

    if (fromLoc.y > toLoc.y) {
        fromY = toLoc.y;
        toY = fromLoc.y;
    } else {
        fromY = fromLoc.y;
        toY = toLoc.y;
    }

    for(indexX = fromX; indexX <= toX; indexX++) {
        for (indexY = fromY; indexY <= toY; indexY++) {
            sumOfCost += ((struct item*)(arr+indexX))[indexY].cost;
        }
    }
    return sumOfCost;
}

int main() {

    int i, j, row, col;

    printf("Enter number of row: ");
    scanf("%d", &row);
    printf("Enter number of Column: ");
    scanf("%d", &col);

    struct item product[row][col];

    for(i = 0; i < row; i++) {
        for(j = 0; j < col; j++) {
            scanf("%lf", &product[i][j].cost);
        }
    }

    loc fromLoc, toLoc;
    fromLoc.x = 0;
    fromLoc.y = 0;
    toLoc.x = row - 1;
    toLoc.y = col - 1;

    printf("\n\nSum of cost : %.2lf", arraySumLoc((struct item**)(&product), fromLoc, toLoc));
    getch();

    return 0;
}

最佳答案

double arraySumLoc(struct item *arr, loc from Loc, iloc toLoc) {

double sumOfCost = 0.0;     
int fromX, fromY, toX, toY, indexX, indexY;

if (fromLoc.x > toLoc.x) {
    fromX = toLoc.x;
    toX = fromLoc.x;
} else {
    fromX = fromLoc.x;
    toX = toLoc.x;
}

if (fromLoc.y > toLoc.y) {
    fromY = toLoc.y;
    toY = fromLoc.y;
} else {
    fromY = fromLoc.y;
    toY = toLoc.y;
}

for(indexX = fromX + 1; indexX <= toX; indexX++) {
    for (indexY = fromY + 1; indexY <= toY; indexY++) {
        sumOfCost += ((struct item*)(arr+indexX))[indexY].cost;
    }
}
return sumOfCost;

} printf("\n\n成本总和: %.2f", arraySumLoc((struct item**)(&product), fromLoc, toLoc));

关于c - 在 C 中通过引用传递动态长度的二维结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166658/

相关文章:

编译器随机抛出不同的错误

c - C 中的 For 循环循环次数超出了应有的次数。为什么?

c - 程序忽略 if else 语句

python - TypeError:尝试绘制函数时,只能将 size-1 数组转换为 Python 标量

sql - 更改数据类型时进行透视(动态)

c - 如何正确包装带有动态参数数量的函数?

c - 我在 GNU GCC 编译器上运行代码时遇到问题,而它在 VC++ 编译器上运行良好

javascript - 无返回值的函数

c - 如何编写一个可以同时采用动态/静态分配的二维数组的 c 函数?

php - 获取 .htaccess 引导的文件的文件名?