How to copy char *str to char c[] in C?

前端 未结 6 2168
栀梦
栀梦 2020-12-14 04:52

Trying to copy a char *str to char c[] but getting segmentation fault or invalid initializer error.

Why is this code is giving me a

6条回答
  •  难免孤独
    2020-12-14 05:10

    use strncpy to be sure to not copy more charachters than the char[] can contains

    char *s = "abcdef";
    char c[6];
    
    strncpy(c, s, sizeof(c)-1);
    // strncpy is not adding a \0 at the end of the string after copying it so you need to add it by yourself
    c[sizeof(c)-1] = '\0';
    

    Edit: Code added to question

    Viewing your code the segmentation fault could be by the line

    strcpy(c, token)
    

    The problem is if token length is bigger than c length then memory is filled out of the c var and that cause troubles.

提交回复
热议问题