I'm interested in different ways to allocate memory in the heap for bi-dimensional arrays.
It seems like the same notation is used when accessing pointers to pointers and pointers to arrays of one or several dimensions. I was hoping to have someone clarify the difference and the usefulness of each. Are they both right?
This first way would be storing the array as a pointer to pointer:
char **createTable(int r, int c) {
char **table;
int i;
char *offset;
table = malloc(r * sizeof (char *) + r * c * sizeof (char));
if (!table) return NULL;
offset = (char *) table + sizeof (char *) * r;
for (i = 0; i < r; i++) {
table[i] = offset + c * i;
}
return table;
}
This other way seems faster. I can't think of a good way to wrap it in a function like the other one.
char (*table)[c];
table = (char (*)[c]) calloc(r * c, sizeof (char));
Am I right in understanding that even though arrays are like static pointers, arrays have the ability to have several dimensions in themselves?
Is it true that the first way I describe is the orthodox way?
char table[r][c]
? I guess your intention is that is will be possible to return the pointer from the function that allocates it? It might be useful to make this clear in the question so we know why you're not just doingchar table[r][c];
– Aaron McDaid Nov 21 '13 at 21:11table
, wheretable
ischar (*table)[c];
from a function that returnschar**
. Clang:incompatible pointer types returning 'char (*)[c]' from a function with result type 'char **'
– Aaron McDaid Nov 21 '13 at 21:12char**
but I don't know how to return it with it's own type or even return it via a return argument. Even if longer the first option has a simpler type as far as syntax complexity, what do you think? – niic Nov 21 '13 at 21:25offset = (char *)(table + r)
is cleaner. – paddy Nov 21 '13 at 21:59