malloc matrix which points to malloc arrays(C) -
edit: should not use [].
i have defined integer n value 5 , *malloc.
#define n void* malloc (size_t size); ...
int *p_mat=(int*)malloc(sizeof(int*) * n); this matrix.
now need arrays.
int p_arr1=(int)malloc(sizeof(int) * 4); int p_arr2=(int)malloc(sizeof(int) * 3); int p_arr3=(int)malloc(sizeof(int) * 1); int p_arr4=(int)malloc(sizeof(int) * 2); int p_arr5=(int)malloc(sizeof(int) * 5); so have 5 arrays in different sizes. how make each pointer of matrix point first cell in array?
and question, how send these variables function, mean - parameters in function key?
an array of n pointers arrays-of-integers of different sizes.... (note don't cast malloc return value in c - can hide errors - see do cast result of malloc?).
int = 0; int *p[n]; size_t sizes[] = { 4, 3, ..., 5 }; // n sizes for(; < n; ++i) { p[i] = malloc(sizeof(int) * sizes[i]); } now p array of pointers-to-int. p[n] therefore nth pointer-to-int in array.
int *p[n] in memory:
int *p[n] +-----+ | | <------- each element of array pointer-to-an-integer | | +-----+ | | | | +-----+ . . . +-----+ | | | | +-----+ when p[n] = malloc(sizeof(int) * sizes[i]), saying pointer p[n] (remember each element of array p pointer), points block of memory size of sizes[i] integers. like...
+-----+ +------+------+ ... +------+ |p[n] |-------- array element pointer ---> | int1 | int2 | | intm | | | | | | | | +-----+ +------+------+ ... +------+ . . . +-----+ | | | | +-----+ so when write p[n] accessing pointer array of ints malloc()ed...
later on in code must remember free() memory allocated :)
for(; < n; ++i) { free(p[i]); } hope helps...
edit: didn't read last bit of question wilsonmichaelpatrick has answered it...
edit: note, btw, i'm not checking malloc() return null , handling possible error example...
if not want declare int *p[n]; on stack , prefer heap, try following...
int = 0; size_t sizes[] = { 4, 3, ..., 5 }; // n sizes int **p = malloc(sizeof(int *) * n); for(; < n; ++i) { p[i] = malloc( sizeof(int) * sizes[i]); } ... ... for(; < n; ++i) { free(p[i]); } free(p); edit: use #include <stdlib.h> definitions of free() , malloc()
Comments
Post a Comment