Click here to Skip to main content
15,029,596 members
Please Sign up or sign in to vote.
4.20/5 (2 votes)
See more:
How does memory allocation in C and C++ arrays work?
Updated 26-Jan-11 9:28am
Andrew Brock 22-Jan-11 0:16am
What do you mean, What is the first memory address returned? or the memory points to the first element in an array or what?
kundansinha15 22-Jan-11 0:22am
i mean in c and c++ memory allocation in array are starts from 0,1 or someone else...
Indivara 22-Jan-11 0:26am
Array index starts from 0 (if that's what you are asking)

Array indices are just a convenient and more meaningful way of doing addition.
Hence the first element in any array, static or dynamic, is 0 as you add 0 to find it.
char *szDynamicStr = new char[12];
strcpy(szDynamicStr, "hello world");
printf("%c == %c\n", szDynamicStr[0], //This accesses the first element ('h') as an array offset
	*(szDynamicStr + 0)); //This accesses the first element as an addition to the pointer value

Both szDynamicStr[0] and *(szDynamicStr + 0) compile to exactly the same code, because the array translates to the pointer offset.

The pointer is pointing to the first element in the array, so offset 0 is the first element, offset 1 is the 2nd element, etc...

If this answers your question and you don't care why it works stop reading here or you might get confused.

When adding a number to a pointer, the number is multiplied by the size of the data that is getting pointed to (in this case 1 byte for a single ASCII char) by the compiler.

This is better explained in code:
DWORD pNumbers[] = { 0xD00D, 0xBADF00D }; //This is still a pointer, it is just easier to allocate this example this way.
printf("%u == %u\n", pNumbers[1], //The 2nd element in the array (0xBADF00D) as you would expect
	*(pNumbers + 1)); //This is also the 2nd element in the array. This actually adds 1 * sizeof(DWORD) = 4 bytes to the pointer in order to get the 2nd element in the array.
When a memory allocation fails with C++'s new operator, it throws an exception.
When a memory allocation fails with C, it returns a null pointer.

When you use new it automatically constructs the objects (the constructor of the object is called).
It's more efficient, but a lot more cumbersome to allocate memory with C (especially if for arrays that you may not need to be initialized/constructed). You can bypass the default constructor, but add a bit of book-keeping for safety.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900