Trying to understand working of char pointer

Status
Not open for further replies.

girish09

Junior Member level 2
Joined
Jul 21, 2012
Messages
20
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Pune
Activity points
1,450
Hello all,
I am trying to understand char pointer. In my program I am having 4 bytes number (12345678) and using char* I am trying to separate, save in char array and print each byte, but I am successful in only first byte (i.e. 78) but as soon as I am trying to print next byte by incrementing char pointer it is displaying garbage value. Please help me where I am going wrong? Please go through my code.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

char a;
int i,j;

int main(void)
{
	  char arr[4] = {0,0,0,0};


		int int_val = 12345678;
		char *ptr;

		ptr = (char*)(&int_val);
		arr[0] =  *ptr;
		printf("%d", arr[0]);

		ptr++;
		arr[1] =  *ptr;
		printf("%d", arr[1]);

		ptr++;
		arr[2] =  *ptr;
		printf("%d", arr[2]);

		ptr++;
		arr[3] =  *ptr;
		printf("%d", arr[3]);
return(0);

}
 
Last edited by a moderator:

Code:
int int_val = 0x12345678;
	  		char *ptr;

	  		ptr = (char*)(&int_val);
	  		arr[0] =  *ptr;
	  		printf("%x", arr[0]);

	  		ptr++;
	  		arr[1] =  *ptr;
	  		printf("%x", arr[1]);

	  		ptr++;
	  		arr[2] =  *ptr;
	  		printf("%x", arr[2]);

	  		ptr++;
	  		arr[3] =  *ptr;
	  		printf("%x", arr[3]);
return(0);

- - - Updated - - -

Problem solved, Thanks a lot aProgrammer,
OUTPUT is 78563412 which is correct. Thanks Easyrider83 for your instant reply, can you tell me how can i use union to do the same process?
 


Refer this Post

https://stackoverflow.com/questions/252552/why-do-we-need-c-unions
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…