简体   繁体   English

分配2d阵列

[英]Allocating a 2d Array

My aim is to allocate a 2d array with only using 1 line for efficiency. 我的目标是分配一个2d数组,只使用1行来提高效率。 Since my prof is expecting it to be efficient. 因为我的教授期望它有效率。 the code gives me an error saying that it can't convert from void* to int. 代码给我一个错误,说它无法从void *转换为int。

#include<stdio.h>
#include<stdlib.h>

#define NUMOFCOL 4

int **addtwoarr(int (*A)[NUMOFCOL], int (*B)[NUMOFCOL]);

int main(void){
    int firstarr[4][4]={{1,1,1,1},
                        {1,1,1,1},
                        {1,1,1,1},
                        {1,1,1,1}},
        secondarr[4][4]={{1,1,1,1},
                        {1,1,1,1},
                        {1,1,1,1},
                        {1,1,1,1}}, **receiver;
    receiver = addtwoarr(firstarr, secondarr);
    printf("%d", receiver[3][3]);
}

int **addtwoarr(int (*A)[NUMOFCOL], int (*B)[NUMOFCOL]){
    int col, row, **arr;
    (*arr)[NUMOFCOL] = malloc(NUMOFCOL * sizeof(*arr)); /*this line in particular gives the error */
    for(row=0; row<NUMOFCOL; row++){
        for(col=0;col<NUMOFCOL; arr[row][col]=A[row][col]+B[row][col], col++){}
    }
    return arr;
}

The allocation happens in the addtwoarr function which is where the error occurs. 分配发生在addtwoarr函数中,这是发生错误的地方。

I seriously don't recommend this, as there are a ton of assumptions in your code about top-end sizing. 我认真不建议这样做,因为您的代码中有大量关于高端大小的假设。 But if you really want to do it, the rather cryptic syntax for returning pointers to fixed length arrays in C looks something like this: 但是如果你真的想要这样做,那么在C中返回指向固定长度数组的指针的相当神秘的语法看起来像这样:

#include <stdio.h>
#include <stdlib.h>

#define NUMOFCOL 4

int (*addtwoarr(int A[][NUMOFCOL], int B[][NUMOFCOL]))[NUMOFCOL];

int main(void)
{
    int firstarr[][NUMOFCOL] = {
        {1,1,1,1},
        {1,1,1,1},
        {1,1,1,1},
        {1,1,1,1}},

    secondarr[][NUMOFCOL] = {
        {1,1,1,1},
        {1,1,1,1},
        {1,1,1,1},
        {1,1,1,1}};

    int (*receiver)[NUMOFCOL] =  addtwoarr(firstarr, secondarr);
    printf("%d\n", receiver[3][3]);
    free(receiver);
}

int (*addtwoarr(int A[][NUMOFCOL], int B[][NUMOFCOL]))[NUMOFCOL]
{
    int col, row;
    int (*arr)[NUMOFCOL] = malloc(NUMOFCOL * sizeof(*arr));
    for(row=0; row<NUMOFCOL; row++){
        for(col=0;col<NUMOFCOL; arr[row][col]=A[row][col]+B[row][col], col++);
    }
    return arr;
}

Output 产量

2

Best of luck. 祝你好运。

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

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