I am trying to fully wrap my mind around malloc and memory allocation. I recently came across a situation that made me raise a brow.
When fiddling with arrays I was creating an array of arrays. Which in my mind would look something like this:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], ...]
When doing this I figured since I needed malloc to create the outer array. I also needed to call malloc for each inner array that I was creating. I quickly realized I get the same output when I skip this step which makes no sense to me.
Consider the following script.
int main(int argv, char* argc[]){
// initialize outer array
int* outer = malloc(5 * sizeof(int));
int i, j;
// for each slot in outer array
// create a new array and assign it
// to that slot.
// NOT NEEDED.
for(i = 0; i < 5; i++){
int* inner = malloc(5 * sizeof(int));
*(outer + i) = *inner;
}
// If I comment out the above four lines
// the output remains the same.
// assign to each slot in each inner array
for(i = 0; i < 5; i++)
for(j = 0; j < 5; j++)
*(outer + i * 5 + j) = j;
// print each element in each inner array
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
printf(
"%d ",
*(outer + i * 5 + j)
);
}
puts("");
}
}
The output from this script is as follows:
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
Which is what I expected. But when I comment out the first for loop in the script I get the same output. Why is this? Do I not need to allocate memory for the inner arrays? Clearly the answer is no but I'm trying to understand why that is.