One problem I have with this code is that it's not clear when this while loop ends.
Code:
while(x[i]) {
if (x[i]) i++;
}
The way things are, the loop needs to end on NULL, or some other sentinel value. I could set it up like so:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const int xDim = 4;
const int yDim = xDim;
int i;
int **x;
x = malloc((xDim + 1) * sizeof x[0]);
for (i = 0; i < xDim; i++) {
x[i] = malloc(yDim * sizeof *x[0]);
memset(x[i], 0, sizeof *x[0] * yDim);
}
x[xDim] = NULL;
for (i = 0; x[i]; i++) ;
printf("%d pointers in x.\n", i);
for (i = 0; x[i]; i++) free(x[i]);
free(x);
return 0;
}
C code - 29 lines - codepad