In: Computer Science
Design a C program to print out the unsigned char (integer) values of the 4 bytes in sequential order (i.e., the first byte is printed first). Using the code framework provided below, the printing is done by the function void byte_value(int *), in which only pointer variables can be declared and used. #include <stdio.h>
void byte_value(int *);
int main() {
int n = 1;
byte_value(&n);
printf("Enter an integer: ");
if (scanf("%d", &n) == 1)
byte_value(&n);
return 0;
}
void byte_value(int *p) {
// fill in the body using only pointer variables
// printout the memory address of the byte and its unsigned char (integer) value
// one line for each pair, a total of 4 lines
return;
}
The function code & a sample output of running the given program is attached below:
(*Note: Please up-vote. If any doubt, please let me know in the comments)
Function Code:
void byte_value(int *p) {
// fill in the body using only pointer variables
// printout the memory address of the byte and its unsigned char (integer) value
// one line for each pair, a total of 4 lines
unsigned char* cp = p; //create pointer of type unsigned char and point it to same address as p
printf("%p \t %u\n",cp,*cp); //print memory address of first byte & its unsigned char (integer) value
printf("%p \t %u\n",cp+1,*(cp+1)); //print memory address of second byte & its unsigned char (integer) value
printf("%p \t %u\n",cp+2,*(cp+2)); //print memory address of third byte & its unsigned char (integer) value
printf("%p \t %u\n",cp+3,*(cp+3)); //print memory address of fourth byte & its unsigned char (integer) value
return;
}
Output Screenshot: