I'm trying to to create the follow data structure:
{}
= dynamic memory allocation
[]
= array
{[ptr, ptr, ptr], [ptr, ptr, ptr], ...}
and a memory allocation to track the size of the memory locations that the ptr
's will point at:
{[int, int, int], [int, int, int], ...}
and then pass this data structure into a function such that the values of the inner ptr
's and int
's are changed from within the function.
I hoped something like this would work:
void foo(int **arr[3], int *sizes[3], int num_arrays)
{
int i, j, k;
for(i=0; i<num_arrays; i++)
{
for(j=0; j<3; j++)
{
sizes[i][j] = 1 + (i * j);
arr[i][j] = malloc(sizeof(int) * sizes[i][j]);
for(k=0; k<sizes[i][j]; k++)
{
arr[i][j][k] = i * j * k;
}
}
}
}
int main(int argc, char *argv[])
{
int **arr[3] = malloc(sizeof(*(int[3])) * 10); //line 33
int *sizes[3] = malloc(sizeof(int[3]) * 10); //line 34
foo(arr, sizes, 10);
int i, j, k;
for(i=0; i<10; i++)
{
for(j=0; j<3; j++)
{
for(k=0; k<sizes[i][j]; k++)
{
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
Unfortunately this results in compiler errors:
main.c: In function ‘main’:
main.c:33:41: error: expected expression before ‘)’ token
int **arr[3] = malloc(sizeof(*(int[3])) * 10);
^
main.c:34:19: error: invalid initializer
int *sizes[3] = malloc(sizeof(int[3]) * 10);