c - how does this memcpy code works -


hi came across simple c programm cant understand how code works:

#include <string.h> #include <stdio.h>  char *a = "\0hey\0\0";   /*  6 */ char *b = "word\0up yo"; /* 10 */ char *c = "\0\0\0\0";    /*  4 */  int main(void) {     char z[20];     char *zp = z;      memcpy(zp, a, strlen(a)+1);      memcpy(zp, b, strlen(b)+1);      memcpy(zp, c, strlen(c)+1);     /* z contains 20 bytes, including 8 nulls */     int i;  for(i = 0; < 20; i++){     if (z[i] == 0){             printf("\\0");       }     printf("%c", z[i]);}     return 0; } 

i expecting printing z output :

\0hey\0\0\0word\0up yo\0\0\0 

but instead im getting :

\0ord\0\0\0\0\0\0\0\0\0\0\0\0???z 

finally , when print instead of z right output. can explain me why happens ? in advance.

edit: how concatenate such strings?

strings in c zero-terminated; functions in standard c library assume property. in particular, function strlen returns number of non-zero characters start of string. in example, strlen(a) equal 0, first character of a zero.

the code have following effect:

 memcpy(zp, a, strlen(a)+1); 

now zp still contains \0, because strlen(a) 0, 1 character copied.

 memcpy(zp, b, strlen(b)+1); 

now zp contains word\0: 5 characters copied.

 memcpy(zp, c, strlen(c)+1); 

now first character of zp overwritten, contains \0ord\0.

finally , when print instead of z right output. can explain me why happens ? in advance.

that's because a, b, , c happen allocated sequentially in memory. when print "20 bytes starting start of a", you're looking @ memory past latest byte of a. memory happens contain b. start reading b. same goes b , c. note no means guaranteed. looking past memory allocated char * in fact instance of undefined behaviour.

how concatenate such strings?

in general, there no way how find length of such "strings" in runtime. not call them strings such, since "string" has specific meaning in c language - refers 0 terminated strings, while your's regions of memory.

however, since know size @ compile time, can use that. avoid magic numbers in code, it's better use char arrays instead of char pointers, because can use sizeof operator. however, note string literals in c implicitly 0 terminated! fit result in 20-byte buffer, you'll want use sizeof(x) - 1:

char a[] = "\0hey\0\0";   /*  6 */ char b[] = "word\0up yo"; /* 10 */ char c[] = "\0\0\0\0";    /*  4 */  memcpy(zp, a, sizeof(a) - 1); zp += sizeof(a) - 1; memcpy(zp, b, sizeof(b) - 1); zp += sizeof(b) - 1; memcpy(zp, c, sizeof(c) - 1); 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -