girish09
Junior Member level 2
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.
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: