tags:

views:

126

answers:

6
+2  Q: 

Pointer Question

Hi,

Can you please explain to me what is happening here?

char data[128]; // Create char array of size 128.
long * ptr;     // Create a pointer.
ptr = (long *) data;   // ??

Mainly, what does the (long *) mean?

Does it mean that the data is of type char, and I am casting the reference to data as a reference to a long?

Thank you.

A: 

(long *) is a typecast. Since data is an array of char, this typecast is needed to make the assignment to ptr, which is a long * pointer. Your "does it mean" sentence is correct.

Carl Norum
A: 

This statement means, take data (which is the memory address of the start of 128 chars), and treat that memory address instead as the start of a long number.

This seems very risky and foolish.

Is there any particular reason this is being done?

abelenky
A: 

(long *) is a cast. It tells the compiler "this here char[128] you've got? Treat it as a long *." But then you assign that to a char * pointer, which a) is an invalid assignment without a cast from long * to char *, and b) won't preserve the... longitude... of the variable.

Basically, it's pointless in this particular example. I suspect it's because you've modified the original code for display here--can you show us what it actually looks like?

Jonathan Grynspan
+3  A: 

The (long*) expression is a C style cast. It treates the memory pointed to by data and treats it as a pointer to data of type long

JaredPar
+1  A: 

It is a "C-style" cast; in your case, it translates into a "reinterpret cast". Read it as "take a pointer to a char type, and treat it as if it pointed to long". The preferred way to write it is reinterpret_cast<long>(ptr). Note that valid indexes are from 0 to 128 * sizeof(char) / sizeof(long) - 1, which may differ between platforms.

Alex Emelianov
A: 

It is casting the data pointer as a pointer to a long.

The line:

 char data[128];

will allocate 128 bytes of memory and treat that data as characters. The code:

 long * ptr;
 ptr = (long *) data;

allocates a pointer to a long, and sets that pointer to point at the memory allocated by char data[128];.

You can reference this memory by data[x] to get the xth character starting at the beginning of this memory block. Or you can reference this memory by ptr[x] to get the xth long starting at the beginning of this memory block. Just note that each long takes up more storage than each character. It is probably 8 bytes - so you can go up to data[127] or ptr[15].

PatrickV