Engineer999 Engineer999 - 1 year ago 60
C++ Question

Converting arrays of one type to another

Basically I have an array of doubles. I want to pass this array to a function (ProcessData) which will treat them as short ints. Is creating a short pointer and pointing it to the array, then passing this pointer to the function ok (code 1) ?

Is this in effect the same as creating a short array, iterating through each element and converting each element of the double array to a short and then passing the short array pointer (code 2) ? Thanks

//code 1
short* shortPtr = (short*)doubleArr;


//code 2
short shortArr [ARRSIZE];
int i;
for (i = 0; i < ARRSIZE; i++)
shortArr[i] = (short)doubleArr[i];

Answer Source

No you can't do that. Here's at least one reason why:

An array is a contiguous sequence of several memory allocations accessed by way of an index, like so


Note the four dashes inside the square brackets. That is to indicate that in most situations in C/C++, an int is four bytes long. Arrays cells can be accessed by their index because if we know the memory address of the first cell (m) and we know how big each cell is meant to be (c) - in this case, four bytes, we can easily find the memory location of any index by doing m + index * c

^ array[0]

 ----  ----  ^ array[2]

Fundamentally, this is why pointers can be treated like arrays in C/C++, because when you are accessing arrays, you are basically doing pointer arithmetic anyway.

In most cases in C/C++, a short is 2 bytes long, so to represent it in the same way


If you create a short pointer, and try to use it as an array, it is expected to point to something which is arranged like the above. If you try to index it, it is going to have problems: if you were dealing with an array of shorts, the location of array[2] is the same as m + 2 * index, as shown below

 --  --  ^ array[2] (note moving along four bytes)

But since we are in reality dealing with an array of integers, the following will happen

 ----  ^ array[2] (again moving along four bytes)

Which is clearly wrong

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download