My aim is to allocate a 2d array with only using 1 line for efficiency. 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.
#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.
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:
#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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments