C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 07-21-2009, 10:39 PM   #1
Registered User
 
Join Date: Jul 2009
Location: Kerala, India
Posts: 3
Thumbs up Program on pointers - explanation needed

Hi

Code:
   main ()
   {
      int a[] = {10,60,30,40,50};
      char *p;
      p = (char *)a;
      printf("%d",*((int *)p+4));
   }
The ouput of this code is 50. I know why this output is obtained. Now take a look at the next piece of code

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   Reply With Quote
Old 07-21-2009, 10:48 PM   #2
Guest
 
Sebastiani's Avatar
 
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   Reply With Quote
Reply

Tags
pointers, type-casting

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 01:24 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22