Re: how to convert from long to short in vc++?



<teopeggy@xxxxxxxxx> wrote in message
news:1136186662.775444.147700@xxxxxxxxxxxxxxxxxxxxxxxxxxxx
> hi,
> i'd like to know how to convert a pointer variable from long to short?
>
> how to solve this error below
> error C2440: '=' : cannot convert from 'long *' to 'short *'
>
> please help.i need it for my project
>
> regards
> peggy

Doesn't the VC++ error message tell you what is required? I get:

cannot convert from 'long *' to 'short *'
Types pointed to are unrelated; conversion requires reinterpret_cast,
C-style cast or function-style cast

The first of these is illustrated below:

int main()
{
long *ptr_long = new long;
short *ptr_short = reinterpret_cast<short*>(ptr_long);

delete ptr_long;
return 0;
}

Note that the compiler has good reasons for giving you this error and you
should only override it with a cast if you really know what you are doing.
The fact that you need to ask this question makes me doubt it. To illustrate
the dangers, suppose that the pointer points to an array of longs, rather
than a single long and consider the following program:

#include <iostream>
using namespace std;

int main()
{
long *ptr_long = new long[10];
short *ptr_short = reinterpret_cast<short*>(ptr_long);

// set element i equal to i
for(int i=0; i<10; ++i)
ptr_long[i] = i;

cout << "Output longs\n";
for(int i=0; i<10; ++i)
cout << ptr_long[i] << endl;

cout << endl << endl;

// now use the cast to treat the array of longs as if it
// were an array of shorts
cout << "Output shorts using array initialised as longs\n";
for(int i=0; i<10; ++i)
cout << ptr_short[i] << endl;

cout << endl << endl;

// Repeat the above but interchange
// ptr_long and ptr_short
// set the ith short equal to i
for(int i=0; i<10; ++i)
ptr_short[i] = i;

cout << "Output shorts\n";
for(int i=0; i<10; ++i)
cout << ptr_short[i] << endl;

cout << endl << endl;

cout << "Output longs using array initialised as shorts\n";
for(int i=0; i<10; ++i)
cout << ptr_long[i] << endl;

delete[] ptr_long;
return 0;
}


--
John Carson


.



Relevant Pages