C compound literals, pointer to arrays

First, the casts are redundant in all of your examples and can be removed. Secondly, you are using the syntax for initializing a multidimensional array, and that requires the second dimension the be defined in order to allocate a sequential block of memory. Instead, try one of the two approaches below:

  • Multidimensional array:

    int p[][3] = {{1,2,3},{4,5,6}};
    
  • Array of pointers to one dimensional arrays:

    int p1[] = {1,2,3};
    int p2[] = {4,5,6};
    int *p[] = {p1,p2};
    

The latter method has the advantage of allowing for sub-arrays of varying length. Whereas, the former method ensures that the memory is laid out contiguously.

Another approach that I highly recommend that you do NOT use is to encode the integers in string literals. This is a non-portable hack. Also, the data in string literals is supposed to be constant. Do your arrays need to be mutable?

int *p[] = (int *[]) {
    "\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00",
    "\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00"
};

That example might work on a 32-bit little-endian machine, but I’m typing this from an iPad and cannot verify it at the moment. Again, please don’t use that; I feel dirty for even bringing it up.

The casting method you discovered also appears to work with a pointer to a pointer. That can be indexed like a multidimensional array as well.

int **p = (int *[]) { (int[]) {1,2,3}, (int[]) {4,5,6} };

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)