Gianni Caringi Gianni Caringi - 11 days ago 5
C Question

Someone can explain the code?

I have to assign to the variable "j" value of the variable "i" using only a pointer to char. I couldn't write code, so I see this solution but I don't understand what happen in the "for" body. Can someone explain it to me?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char **argv) {
int i = 10;
int j = 20;
char *p, *q;

p = (char*)&i;
q = (char*)&j;

for(int k = 0; k < sizeof(i); ++k) {
*(q + k) = *(p + k);
}

printf("%d == %d\n", i, j);

return 0;
}

Answer

Due to these statements

p = (char*)&i;   
q = (char*)&j;

objects i and j are considered (interpreted) like character arrays that have sizeof( int ) characters. And in this loop

for(int k = 0; k < sizeof(i); ++k) {  
    *(q + k) = *(p + k);    
}

these characters are copied from the integer variable i to the integer variable j byte by byte.

As for these expressions *(q + k) and *(p + k) the they are fully equivalent to q[k] and p[k]. Thus the loop can be rewritten using this syntax

for(int k = 0; k < sizeof(i); ++k) {  
    q[k] = p[k];    
}