C++/more on allocation
Expert: vijayan - 7/31/2009
QuestionHi 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
AnswerIt 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