- #1
Epic Sandwich
- 25
- 0
So I'm learning C, and I think I'm doing pretty well so far. Anyway, I'm up to Arrays, and some code that was posted in the tutorial is this:
The thing that's confusing me is this. So first, you define a pointer variable, (myArray), and you make it point to some memory with malloc. So now, the pointer contains the address to some data that can hold 20 ints. All correct so far?
Anyway, when myArray[5] comes along, they simply treat the pointer like an array. What I don't i understand is this. How can a variable holding a pointer to some data be an array? I thought you would have to declare an array, and then tell it to go into the data that you just allocated with malloc.
Or, is it not really an array? By saying myArray[5], are you simply referring to the sixth block of memory in the myArray section which was just allocated?
I hope I didn't word this question in a confusing way, I'm just trying to go through C making sure I understand everything instead of rushing through.
Thanks.
Code:
#include <stdlib.h>
int main()
{
int* myArray = malloc( sizeof(int) * 20 ); // could write int myArray[20]; instead.
myArray[5] = 42;
// ... do something else here.
free( myArray ); // Give up ownership once we're done.
return 0;
}
The thing that's confusing me is this. So first, you define a pointer variable, (myArray), and you make it point to some memory with malloc. So now, the pointer contains the address to some data that can hold 20 ints. All correct so far?
Anyway, when myArray[5] comes along, they simply treat the pointer like an array. What I don't i understand is this. How can a variable holding a pointer to some data be an array? I thought you would have to declare an array, and then tell it to go into the data that you just allocated with malloc.
Or, is it not really an array? By saying myArray[5], are you simply referring to the sixth block of memory in the myArray section which was just allocated?
I hope I didn't word this question in a confusing way, I'm just trying to go through C making sure I understand everything instead of rushing through.
Thanks.