First things first : do not cast the return value of malloc in C. This is not your code, but anyway, it is always good to say.
Also, the loops should be rewritten like so : for(i = 1; i < 10; i++)
or maybe for(i = 0; i < 10; i++)
. i = i
is probably an error (what is that website, again ?), and I will assume so.
char **p;
int i;
p = malloc(10*sizeof(char*));
*p = malloc(10*sizeof(char));
for(i = 1; i < 10; i++)
p[i] = p[0] + 10*i;
This first code allocates 10 char*
to p
, and then 10 char
to *p
, which is equivalent to p[0]
. Then, it puts the addresses of an unallocated 2D array into the other values of p[i]
for i from 1 to 9. Since the array is not allocated (or only partially - p[0]
is allocated), this is pretty bad.
char **p;
int i;
p = realloc(p, 10*sizeof(char*));
*p = realloc(p, 10*sizeof(char));
for(i = 1; i < 10; i++)
p[i] = p[0] + 10*i;
This second code uses realloc
instead of malloc
, which does not solve the previous problems, but also adds probable segmentation faults : realloc
on an uninitialized pointer is a bad idea.
char **p = NULL;
int i;
p = malloc(10*sizeof(char*));
*p = malloc(10*sizeof(char));
for(i = 1; i < 10; i++)
p[i] = realloc(p[i-1], 10*i*sizeof(char));
This third code does the same as the first one for the first part, but then uses realloc
on p[i]
for i starting with 0. I assume realloc
deallocates the pointer you pass to it, so this is not really a good idea. And the 10*i*sizeof(char)
is not a good idea either. Basically, you will have p[9]
allocated with 90 char
, and nothing else. And, by the way, initializing p
to NULL
here doesn't do anything.
char **p;
int i;
p = malloc(10*sizeof(char*));
for(i = 0; i < 10; i++)
p[i] = malloc(10*sizeof(char));
This fourth code has something good at least : it allocates separately each p[i]
for i from 0 to 9 (I assume i starts with 0 here, unlike in the other codes). So, this might be the answer you are looking for.
Finally, the question is badly formulated since none of these codes have the same semantics as a declaration like char p[10][10]
.
Edit :
If you want a dynamically allocated 2D array, you can use this for instance :
int i;
char **p = malloc(10 * sizeof *p);
for(i = 0; i < 10; i++)
p[i] = malloc(10 * sizeof *p[i]);
You can also, as cmaster did, use a pointer to an array type (like char[10]
). This is the exemple from cmaster : char (*p)[10]
.