Page 1 of 1
Pointers/addresses
Posted: Sat Feb 01, 2003 7:34 am
by Whatever5k
I want to have a pointer to a certain address in C. What about this:
Code: Select all
unsigned long *p
p = (unsigned long*) malloc(10);
Now I want to have a pointer that has (value of p + 10) as value. Can you follow me? An example:
p points to the address 10. p2 (the second pointer) is supposed to point to the address 20 (p + 10)...
How can I realize this in C? Seems simple, but I've tried many different possibilities -> did not work...
anybody can help?
thanks and best regards,
A. Blessing
Re:Pointers/addresses
Posted: Sat Feb 01, 2003 11:36 am
by ark
Do not do what you just posted in a real program. Ever.
An unsigned long is 4 bytes in length, and you've allocated 10 (not a multiple of 4) bytes for the pointer.
Probably what you want is this:
Code: Select all
unsigned char* p;
p = reinterpret_cast<unsigned char*>(malloc(11));
// or p = (unsigned char*) malloc(11); if you're not using C++
unsigned char* p2 = p + 10;
If you only allocate 10 bytes and p points to the address 10, then only the addresses 10, 11, 12, 13, 14, 15, 16, 17, 18, and 19 validly belong to that pointer.
Keep in mind that pointers and arrays are very closely related. p + 10 is essentially equivalent to p[10]. When you add to a pointer by saying p + 10 and p is of type unsigned long*, you're actually telling your program to advance p by 10
unsigned longs, i.e. 40 bytes.
Re:Pointers/addresses
Posted: Sat Feb 01, 2003 11:39 am
by ark
correction: p[10] is actually equal to *(p + 10). p + 10 is equal to &p[10].
Re:Pointers/addresses
Posted: Sat Feb 01, 2003 1:14 pm
by Whatever5k
Thanks
Re:Pointers/addresses
Posted: Wed Feb 05, 2003 5:53 pm
by Tim
Joel wrote:Code: Select all
unsigned char* p;
p = reinterpret_cast<unsigned char*>(malloc(11));
// or p = (unsigned char*) malloc(11); if you're not using C++
unsigned char* p2 = p + 10;
Pedantic point: if you're using C, you shouldn't cast the value returned from malloc. It's not necessary, and it can be harmful in that code with a cast like this won't give you a warning if you forget to include <stdlib.h>.
This is sufficient: