Originally Posted By: jcl
Here's the solution to the user quiz. Aside from the memory bug, there's one main problem. A one dimensional array is indeed identical to a pointer, but a multi dimensional array is not. int array[x][y] is very different to int **array. In fact a pointer to a pointer is no array at all.

Whenever you access this construct, the program hits two different memory areas. This is much slower than using an array, which is a single contiguous memory area. There are further subtle problems with this coding style, so better don't use it in a real application.

If you do, you must use brackets, and you should use them even when not required by the language syntax. Otherwise either you or some other poor fellow working with your code will confuse this construct with a real multidimensional array, and then you'll get the nicest bugs and crashes.

To be on the safe side, use a normal multidimensional array for a static definition, and a single pointer for a dynamic definition, no matter how many dimensions.


Really? REALLY? This sounds weird. In fact, afair I learned that multidimensional arrays are nothing else than an array of pointers to other arrays, which don't necessarily have to be in one contiguous memory area.
However, if this is true, what you say, why can I use pointers to pointers in function parameters if I want to pass an array to a function? And if that makes a difference, then Lite-C should support arrays with indefinite size as function parameters.
However, I think whenever I saw an example how to create a multidimensional array at runtime, it was always like Rackscha did it. If it is true what you say creating a "real" multidimensional array would look like this:
Code:
int** create_2darray (int sx, int sy)
{
	int** array;
	int* p = malloc(sx*sy*sizeof(int)+sx*sizeof(int)); // allocate one single contiguous memory area (for the data and the pointers)
	array = p; // set the array pointer to its beginning
	int i;
	for(i=0;i<sx;i++) array[i] = p+sx+sy*i; //fill the beginning of the memory with pointers to the 1-dimensional pointers
	return(array);
}


Is that right? But in this case, the pointers to the arrays would be a waste of memory in comparision to a 1-dimensional array of the size sx*sy.