0

I have a structure that contains a pointer to a 2d-array that will be allocated in an initialization function. It's also important to allocate this array in a contiguous block of memory.

I know to allocate a contiguous block of memory as a 2d-array like this:

double (*array)[cols] = malloc(rows* sizeof *array);

However I need to do this on an already declared variable. For example:

typedef struct {
    double **data;
    /* other members */
} MyType;

MyType* init_function(/* args */)
{
    /* more initializing */
    MyType* foo = malloc(sizeof(MyType));

    double (*array)[3] = malloc(3 * sizeof(*array));
    foo->data = array;
    /* more initializing */
}

I would think this would work, but my program crashes as soon as it attempts to either read or write from foo->data. I've printed the pointer address to both array and foo->data and they are identical, and I'm also able to print the contents of array, however attempting to access foo->data[0][0] causes the program to crash. I'm unsure why this won't work, or how to allocate the memory in this fashion on foo->data which is already declared.

qbizzle68
  • 25
  • 6
  • 3
    That won't work for `data`, as it's really an array of *pointers* rather than an array of arrays. `data` is similar to a [*jagged array*](https://en.wikipedia.org/wiki/Jagged_array). See e.g. [this old answer of mine](https://stackoverflow.com/questions/18440205/casting-void-to-2d-array-of-int-c/18440456#18440456) for the difference between the two. – Some programmer dude Nov 26 '22 at 09:24
  • 1
    `double (*array)[3] = malloc(3 * sizeof(*array));` Your compiler warned you about this assignment. You should not have proceeded to run the program. – n. m. could be an AI Nov 26 '22 at 09:25
  • 3
    @n.m.: Why do you think the compiler warned about `double (*array)[3] = malloc(3 * sizeof(*array));`? Did you mean `foo->data = array;`? – Eric Postpischil Nov 26 '22 at 09:27
  • @EricPostpischil yes sorry copied the wrong line. – n. m. could be an AI Nov 26 '22 at 10:28
  • yep, totally glossed over the warning. should have seen that – qbizzle68 Nov 26 '22 at 20:06

1 Answers1

1

The type of data member must be the same as the allocated object. It must be a pointer to 3 element array of double.

typedef struct {
    double (*data)[3];
    /* other members */
} MyType;
tstanisl
  • 13,520
  • 2
  • 25
  • 40