简体   繁体   中英

I need to copy string, but it doesn't work

I need to copy piece to piece1 But I've got an error uninitialized local variable piece1 used

char* piece = strtok(mp[rech], " ");
while (piece != NULL) { 
    char* piece1;
    strcpy(piece1, piece);
    piece = _strrev(piece);
    printf("%s ", piece1);
    printf("%s ", piece);
    piece = strtok(NULL, " ");
}
  • Code passes uninitialized pointer to strcpy() resulting in undefined behavior (UB).

     char* piece1; strcpy(piece1, piece); // Value in pointer piece1 is not valid
  • Tip: enable all warnings. Receive something like

    warning: 'piece1' is used uninitialized [-Wuninitialized]

I think you can use:

while (*piece1++ = *piece++);

You are going through the entire string and coping it to piece1 I had to do a similar thing and this should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM