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.
CodePudding user response:
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;