1

This is dumb, but I'm having trouble getting the right type signature or something. I want to have a function return a two-dimensional array (fixed size on one dimension, variable on the other) but I'm doing something wrong. Minimal example:

void useit(unsigned long sz) {
    uint32_t arr[sz][8] = makeit(sz);
    // Do something useful with arr here
}

// Stub function for allocating and filling an array
uint32_t (*makeit(ulong sz))[8] {
    uint32_t (*arr)[8] = malloc(8*sz*sizeof(int));
    int i, j;
    for (i = 0; i < sz; i++) {
        for (j = 0; j < 8; j++) {
            arr[i][j] = 10*i+j+11;
        }
    }
    return arr;
}

But I don't have the signature right, because gcc complains:

error: incompatible types when assigning to type 'uint32_t[8]' from type 'uint32_t (*)[8]'

Charles
  • 11,269
  • 13
  • 67
  • 105
  • What is the `(*makeit(ulong sz))[8]` supposed to do? – tkausl Feb 04 '16 at 17:45
  • 1
    @tkausl: It's trying to be the signature of the function `makeit` which returns a pointer to `arr` (or something like that). – Charles Feb 04 '16 at 17:47
  • I see... looks like gibberish to me but maybe this helps: http://stackoverflow.com/questions/1453410/declaring-a-c-function-to-return-an-array – tkausl Feb 04 '16 at 17:49

1 Answers1

3

You cannot use:

uint32_t arr[sz][8] = makeit(sz);

since VLAs may not be initialized.

Use:

uint32_t (*arr)[8] = makeit(sz);

See it working at http://ideone.com/iuqtlJ.

R Sahu
  • 204,454
  • 14
  • 159
  • 270