![]() |
| | #1 |
| Registered User Join Date: Jul 2009 Location: Kerala, India
Posts: 3
| Code: main ()
{
int a[] = {10,60,30,40,50};
char *p;
p = (char *)a;
printf("%d",*((int *)p+4));
}
main () { int a[] = {10,60,30,40,50}; char *p; p = (char *)a; printf("%d",*((int *)(p+4))); } The output of this code is 60. I need the explanation for this output. I know this is something to do with type-casting. Kindly explain the output in terms of the number of bytes moved on adding 4 to reach the element '60' in the array a[]. Regards, TheLink |
| thelink123 is offline | |
| | #2 |
| Guest Join Date: Aug 2001
Posts: 4,923
| >> I need the explanation for this output. I know this is something to do with type-casting. When you add an offset to a pointer it advances a number of bytes equal to the the offset multiplied by the size of the type. So if 'p' is a char* then p + 4 == ((char*)p) + (4 * sizeof(char)) == 4 bytes (on most systems) in advance, whereas if 'p' is an int* then p + 4 == ((char*)p) + (4 * sizeof(int)) == 16 bytes (on most systems) in advance. |
| Sebastiani is offline | |
![]() |
| Tags |
| pointers, type-casting |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Palindrome-kinda program with pointers | porsche911nfs | C++ Programming | 27 | 04-23-2009 09:16 PM |
| Client-server system with input from separate program | robot-ic | Networking/Device Communication | 3 | 01-16-2009 03:30 PM |
| Help needed simple program!! | jigen7 | C++ Programming | 8 | 03-26-2005 09:36 AM |
| pointers | InvariantLoop | C Programming | 13 | 02-04-2005 09:32 AM |
| fopen(); | GanglyLamb | C Programming | 8 | 11-03-2002 12:39 PM |