954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Type Cast

Could anyone please tell me whats happenning in line number 10 and 12. The output of this code is 2 and 0.

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[3]={2,3,4};
 char *p;
 clrscr();
 p=arr;
 p=(char*)((int*)(p));
 printf("%d\n",*p);
 p=(int*)(p+1);
 printf("%d",*p);
 getch();
}
ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

Well, look at what's happening to your pointer and it'll let you know.
I modified your code to do this.

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[3]={2,3,4};
 char *p;
 //clrscr();
 p=arr;
 printf("*p:%d, p: %ld\n",*p, p);
 p=(char*)((int*)(p));
 printf("*p:%d, p: %ld\n",*p, p);
 p=(int*)(p+1);
 printf("*p:%d, p: %ld\n",*p, p);
 //getch();
}


It gave me this.

*p:2, p: 2293552
*p:2, p: 2293552
*p:0, p: 2293553

Let's take it one step further.

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[3]={2,3,4};
 char *p;
 //Int size is 4 on 32-bit so cast arr as char* before adding.
 char *end=((char*)arr)+sizeof(arr);  for(p=(char*)arr;p<end;p++){
  printf("*p:%d, p: %ld\n",*p, p);
 }
 //getch();
}

Which, on a little-endian 32-bit system yields:

*p:2, p: 2293548
*p:0, p: 2293549
*p:0, p: 2293550
*p:0, p: 2293551
*p:3, p: 2293552
*p:0, p: 2293553
*p:0, p: 2293554
*p:0, p: 2293555
*p:4, p: 2293556
*p:0, p: 2293557
*p:0, p: 2293558
*p:0, p: 2293559

(Notice that the pointer shifted from 2293552 to 2293548. This is unimportant except to know that there are differences between the two programs.)

Hopefully, this is clear as mud and just as tasty.

Happy coding!

DeanMSands3
Junior Poster
185 posts since Jan 2012
Reputation Points: 37
Solved Threads: 26
 

DeanMSands3.....Thanks a Lot...........

ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You