'table' is a 2-D pointer. First understand what is a 2D pointer. A pointer is a special type of variable that is used to store the address of another variable. So a 2D pointer is a special variable that is again used to store the address of a pointer variable.
Now imagine that you have a single array of pointers(collection of base address of different 1-D array), that will store the base address of many 1-D arrays.
To dynamically allocate memory to this array of pointers you need the statement
table=(int**)malloc(sizeof(int*)*xs);
Now you have an array with 'xs' number of elements, and you can access each element by table[0], table[1], table[2]..and so on..., but none of these arrays is allocated memory. So you need to allocate memory to each of the array individually using a loop like this:
for(i=0;i<xs;i++)
table[i]=(int*)malloc(sizeof(int)*ys);
So your over-all program becomes:
int **table; // table is a 2D pointer
table=(int**)malloc(sizeof(int*)*xs);
for(i=0;i<xs;i++)
table[i]=(int*)malloc(sizeof(int)*ys);
for(i = 0; i < ys; i++)
{
for(j = 0; j < xs; j++)
{
table[i][j] = j * i;
}
}
return table;
You don't need to free the array before returning it. Doing so will make your pointer 'table' a dangling pointer that is still referring to a memory that is no longer allocated, so just return 'table' without the statement:
free(table);
The above statement will lead to a dangling memory that has no access point, ans so is useless. This is a memory leakage problem that arises when memory gets accumulated, and this memory is no more accessible through your program and could not be relocated for other purpose, such a memory is called dangling memory.
one shot. first allocate memory totable, thentable[i](s).returning something that was justfreed?