when you do new foo[x] where 'foo' is a type, it allocates room for 'x' instances of that type. Different types have different sizes... therefore:
1 2 3 4 5 6 7
// assuming sizeof(int) is 4, this will allocate 40 bytes:
// 4 bytes for each of the 10 ints
int* foo = newint[10];
// since sizeof(char) is 1, this will allocate 10 bytes:
// one for each of the 10 chars
char* bar = newchar[10];
Therefore by changing the type you're new'ing, you are allocating more/less bytes.
But this is the important bit....
YOU DO NOT NEED TO USE SIZEOF WITH NEW. That is probably resulting from some old C programmer bringing in malloc practices. That garbage has no place here.
If you want to allocate 'NOMGRPS' pointers... you'd do this:
_Groups = new group*[NOMGRPS];
That's it. Do not multiply by sizeof. The number in the [brakets] is the number of ELEMENTS you want... not the number of bytes. Multiplying by sizeof() transforms it to the number of bytes.
Hi,Disch thanks for your explanation.As I am still very new to c++ I still not really understand these.As for me I just know the basic concept of dynamic allocation. I like to understand thing in graphical view where I know you are not going to do that for me. So if i refering to this http://www.youtube.com/watch?v=i5gUlnrUqqQ is this graphical explanation can give me a better view?
Btw can i say:
_Groups = new group*[NOMGRPS]; is equal to _Groups = (group **) newchar[sizeof (group **) * NOMGRPS]; ?
They're more or less equivalent. It would appear the sizeof() expression in the second version should be sizeof(group*) * NOMGRPS, although it probably doesn't make a difference on existing systems, I don't believe anything in the standard constrains the size of of group* to be the same as the size of group**.
Yes the graphical images he uses in that video to show the memory layouts are pretty good. Although he doesn't mention the number of bytes allocated or sizeof in that tutorial so I'm a little curious where you got that from.
Btw can i say:
_Groups = new group*[NOMGRPS]; is equal to
_Groups = (group **) new char[sizeof (group **) * NOMGRPS]; ?
As cire said, they're similar, but they're not really the same thing. new is type sensitive... not only in the size of the allocated memory, but also in how that memory is constructed. (Likewise, delete[] is type sensitive in how memory is destructed and freed).
You can probably get away with doing something like that in this case since pointers and chars are both basic types... but you really shouldn't do it.
If you find yourself casting with new... or using sizeof() with new... you're doing it wrong.
KISS. Allocate the type you need. If you need an array of ints... then just allocate it as an array of ints. Don't allocate it as chars and then cast it over... that's just extra code, error prone, confusing, and depending on the types, could be fatal.