You are here:

C++/more on allocation

Advertisement


Question
Hi Vijayan,

Thanks again. You say that this code below works in C and C++ alike. But it will only work with int or float, not when the pointer type is MyClass, will it?

This works fine in C++:

//x and y are computed during runtime
array = (int**) malloc(x * sizeof(int**));
for(int i = 0; i < x+1; i++){
array[i] = (int*)malloc(y * sizeof(int*));
}

But I don't think this will work??:

//x and y are computed during runtime
array = (MyClass**) malloc(x * sizeof(MyClass**));
for(int i = 0; i < x+1; i++){
array[i] = (MyClass*)malloc(y * sizeof(MyClass*));
}

Andres

Answer
It will compile in C++ with any pointer.

In both C and C++, it is semantically incorrect. Correct would be:

//x and y are computed during runtime
array = (int**) malloc(x * sizeof(int*));
for(int i = 0; i < x+1; i++){
array[i] = (int*)malloc(y * sizeof(int));
}

and

//x and y are computed during runtime
array = (MyClass**) malloc(x * sizeof(MyClass*));
for(int i = 0; i < x+1; i++){
array[i] = (MyClass*)malloc(y * sizeof(MyClass));
}

Also, semantic correctness required that MyClass must be a POD struct type. see: http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.