I am aware that this is a C++ forum, and I am also aware that most C++ programmers started with C , so I am almost guaranteed people reading this know what I am talking about.
My calculation is correct, I think you just overlooked that the previous line of code before the calculation is "cols *= sizeof(Type)" so by the time the calculation is reach the "cols" is actually cols * sizeof(Type). Anyway if I used yours or mine both are correct.
But there is a problem that I overlooked. And I am not sure if you have overlooked it too.
The equation only works if sizeof(Type*) = sizeof(Type), if not the program crashes.
I would assume my professor knew this so he intentionally put a typedef making sizeof(Type*) != sizeof(Type). Prior to the function there is a typedef which put the sizeof(Type) = 9.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#define ELEMENTS 9
/* Type to use for dynamic array elements... */
//dont know what exactly this is doing but "Type" is a typedefinition of a char[9], so if I say
// Type X, then X is an unsign char X[9].
typedef signed char Type[ELEMENTS];
#undef ELEMENTS
Type **Create2D(size_t rows, size_t cols)
{
Type **primaryPntr, **secondaryPntr, **endPntr;
int rowCount = 0;
primaryPntr = (Type**) malloc(rows * sizeof(Type*) + rows * cols * sizeof(Type));
for(endPntr = primaryPntr + rows, secondaryPntr = primaryPntr; secondaryPntr < endPntr; secondaryPntr++)
{
*secondaryPntr = (Type*)(endPntr + (rowCount * cols));
rowCount++;
}
return(primaryPntr);
}
|
1. if you look on the equation it is composed of " (rows * sizeof(Type*) + rows * cols * sizeof(Type)) " a portion is (Type*) which is a pointer = 4 bytes and another portion is (Type) which according to typedef = 9 bytes.
2. If you look on line 16 of the code you will see that "rowCount * cols" is an offset starting from the pointer "endPntr" and by calculation the new pointer should be "endPntr + (offest by bytes equal to " rowCount * cols * sizeof
(Type))".
but the compiler is offsetting it by " rowCount * cols * sizeof
(Type*))".
My question now is how do I set line 16 so it will offset the endPntr by rowCount * cols * 9 instead of rowCount * cols * 4.