Firkraag wrote:
> Here is the malloc version:
>
> unsigned char **kolor;
> kolor = (unsigned char**)malloc(10 * sizeof(char*));
That creates uninitialised storage for an array of ten pointers to char.
Note that this does not create any storage for the objects being pointed
to.
>
> Now I am not exactly sure which version using new means the same as
> the one using malloc:
>
> 1. unsigned char** kolor = new unsigned char* [10];
Well that also creates an array of ten pointers to char. However you
would normally be much better advised to use std::vector when you need a
dynamic array in C++ because all the handling (such as destruction when
the object goes out of scope) is handled automatically.
Indeed, consider:
std::vector<mytype> foo(){
std::vector<mytype> array;
// work initialising the array
return array;
}
At first sight that function is expensive because it returns a vector by
value. However even today RVO is likely to be sup****ted by your compiler
and that means that the array will not actually be copied but will be
built in the space provided for the return value.
However after C++0x (and even today with some compilers) and move
semantics the cost of copying an std::vector when it is a tem****ary or
about to go out of scope will be very small so given the above function
a statement such as:
std::vector array(foo());
will be cheap and almost free of overhead for the indirection involved.
The biggest payback is that you no longer have to track the lifetime of
the object in order to release the memory when you have finally done
with it.
> 2. unsigned char* kol0 = new unsigned char [10];
That creates an array of 10 unsigned char, a very different beast from
the above.
> unsigned char** kolor = &kol0;
and that creates an extra level of indirection to no purpose and is not
the same thing as either of the original versions of kolor. Indeed it is
a disaster waiting to happen. kolor is now a pointer to a pointer to a
dynamic array and you will almost certainly get its semantics wrong.
>
> Somebody told me, that the first version, because malloc allocates 10
> unsigned char*s here.
No, it allocates storage (uninitialised) for ten unsigned char* on the
heap.
Okay, but what if we used sizeof(char) instead?
Then you would get storage (again uninitialised) for ten unsigned char.
> Something is fishy here. BTW the type "unsigned char" is just an
> example.
You need to get clear in your mind the difference between a pointer and
the thing pointed to.


|