if I were to say
int (*i)[10] = malloc(size(int *) * 5);
this would allocated memory that looks like
{ (int *) , (int *) , (int *) , (int *) , (int *) }
now when I dereference anyone of those pointers I get uninitialized memory,
So other than for accountability reasons, is there any need to include the [10] after (*i) instead of using a double pointers?
Does using the 10 actually allocate space for ten ints, because if it did we wouldn’t be able to access it?
Apologia
There is some confusion, probably on my part; for that, I apologize. From somewhere, presumably the answer by x4u, I copied the notation:
My main answer, immediately following, addresses this C statement. There is a section a mile down the page with the subsection title ‘Original Question’ that addresses what is in the question, namely:
A lot of the analysis and commentary in the answer remains valid for the original question.
Answer
Consider the C statement:
The type of
arris ‘pointer to array of 10int‘. Therefore, the value ofsizeof(*arr)is10 * sizeof(int). Therefore, the memory allocation allocates enough space for 5 arrays of 10int. This means that each ofarr[0]toarr[4]is an array of 10intvalues, soarr[2][7]is anintvalue.How to demonstrate this? Some code, I suppose using C99
printf()formats. It compiles cleanly and runs cleanly undervalgrind.Example code: pa.c
Compilation and trace
Testing on MacOS X 10.7.2 with GCC 4.6.1 and Valgrind 3.7.0.
Original question
The actual question, it seems, was about the allocation:
The type of
iis the same as the type ofarr, a pointer to an array of 10intvalues.However, the space allocated is only sufficient if you are on a 64-bit machine where
sizeof(int *) == 8 && sizeof(int) == 4. Then you have (coincidentally) allocated enough space for one array.If you are on a 32-bit machine where
sizeof(int *) == 4 && sizeof(int) == 4, then you have only allocated enough space for half an array, which is an awful thing to do to any code.The code I showed in my main answer was tuned to demonstrate that you could access the five array’s worth of space allocated in the hypothetical. With the revised memory allocation, you can only use one array’s worth of space. With that change, the rest of my commentary applies unchanged.