Home > Blockchain >  Unable to return a type struct in C
Unable to return a type struct in C

Time:11-26

I have the following struct and function. After allocating a 2D array, I want to return it but for some reason I keep getting the error: "warning: returning ‘int **’ from a function with incompatible return type ‘Array *’ {aka ‘struct array *’} [-Wincompatible-pointer-types]"

typedef struct array
{
    int n1;
    int n2;
    int *data;
} Array;


    Array *array_create(int n1, int n2)
    {
    
     int **arr = malloc(n1 * sizeof(int*));
      for (int i = 0; i < n1; i  )
      {
       arr[i] = malloc(n2*sizeof(int));
      }
    
      Array values = {n1, n2, *arr};
    
        return values;
    }

Here's some code from the main function for some clarity:

{
    Array *arr = array_create(4, 4);

    int cnt = 1;
    for (int i = 0; i < 4; i  ) {
        for (int j = 0; j < 4; j  ) {
            array_set(arr, i, j, cnt  );
        }
    }

CodePudding user response:

I believe you want to return a pointer to your struct, so you have to malloc it first:

const Array *values = malloc(sizeof(*values));
return values

And if you want your Array to be const you need to change the function declaration:

const Array *array_create(int n1, int n2)

and the variable declaration in the main function:

const Array *arr = array_create(4, 4);

CodePudding user response:

  1. you do not allocate a 2D array only array of pointers.
  2. Use the correct types of sizes (size_t)
  3. Your pointer has the wrong type.

I would do it different away to avoid complicated malloc patterns.

typedef struct array
{
    size_t rows;
    size_t cols;
    int data[];
} Array;

Array *array_alloc(size_t rows, size_t cols)
{
    Array *array = malloc(sizeof(*array)   rows * cols * sizeof(array -> data[0]));
    if(array)
    {
        array -> rows = rows;
        array -> cols = cols;
    }
    return array;
}


#define ARR(var) ((int (*)[var -> cols])(var -> data))

int main(void)
{
    Array *a = array_alloc(10,20);

    for(size_t row = 0; row < 10; row  )
    {
        for(size_t col = 0; col < 20; col  )
        {
            ARR(a)[row][col] = row *1000   col;
        }
    }

    for(size_t row = 0; row < 10; row  )
    {
        for(size_t col = 0; col < 20; col  )
        {
            printf("[]] ", ARR(a)[row][col]);
        }
        printf("\n");
    }
}
  • Related