如何重建给定的malloc序列?

时间:2016-02-25 04:42:43

标签: c algorithm malloc

我必须使用的malloc< dd数组

1 1 1 1 1
1 1 1 1 1 
1 1 1 1 1
1 1 1 1 1

这不是由[] []数组构建的,而是由printf分隔的malloc内存(" \ n");

我想操纵它并使for循环遍历列表,结果是

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 25

所以结果是

第1行*第1-4列 第2行*第1-4栏......

任何帮助都会受到赞赏,我现在有一个大脑放屁(刚下课)

typedef struct array {
    int cols, rows;
    int *arr;
} array;

array mkSum(array node)
{
    int i;
    for (i = 1; i <= ((node.cols) * (node.rows)); i++) //goes through all 25
    {

        //CODE TO MANIPULATE

    }
    for (i = 0; i < ((node.cols) * (node.rows)); i++) //goes through all 25
    {
        if (i % node.cols == 0)
            printf("\n");
        printf(" %d", node.arr[i]); //prints out elements

    }
    return(node);
}

通过传入指向数组的指针来调用mkSum,该数组作为我必须工作的数组(第一个示例)

mkSum(array);

2 个答案:

答案 0 :(得分:0)

问题有点不清楚(特别是关于期望的结果),但我认为对于操作你最好使用两个嵌套循环,并模拟node.arr是一个二维数组:

for (int col = 0; col < node.cols; col++ ) {
    for (int row = 0; row < node.rows; row ++ ) {
        ... Element to modify: node.arr[row * node.cols + col]
    }
}

在此方法中,您必须根据行/列以0开头的事实调整计算公式。

答案 1 :(得分:0)

试试这个