Sunday, 15 February 2015

c - Memcpy integer to buffer -



c - Memcpy integer to buffer -

so have following:

char * buffer = (char *) malloc(2*80 + 4); uint32_t networkedrin = htonl(student->rin); printf("rin %u\n", student->rin); //clear memory , re-create first lastly , rin new buffer memset(buffer, '\0', 164); memcpy(buffer, student->firstname, 80); memcpy(buffer+80, student->lastname, 80); memcpy(buffer+160, &networkedrin, 4); printf("networked rin: %u\n", networkedrin); printf("l5: %s %s %u\n", buffer, buffer+80, buffer+160);

and confused because when printing @ end expected value same networked rin value printed before not, in fact garbage because changing every run. know should using sizeof or whatever told utilize hard coded value of 4 uint32 , not. i'm stuck why i'm getting garbage when trying display networked rin number buffer.

for illustration receiving output after 2 runs of program

rin 60 networked rin: 1006632960 l5: loller cats 16375984 rin 60 networked rin: 1006632960 l5: loller cats 10260656

i'm sure simple can't see it.

buffer+160 not value looking for. buffer+160 a pointer int, not int itself.

you must type-cast , de-reference pointer see value want.

printf("l5: %s %s %u\n", buffer, buffer+80, *(uint32_t*)(buffer+160));

c

No comments:

Post a Comment