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

前端 未结 6 2162
栀梦
栀梦 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条回答
  •  -上瘾入骨i
    2020-12-14 04:52

    It's been a while since i coded in c/c++, but c[80] is probably allocated on the stack. If you use char *c and strdup or similiar you get it allocated on the heap where strtok can access it.

    Try something like this.

    char *token = "some random string";
    char *c;
    c = strdup(token);
    char *broken = strtok(c, "#");
    free(c);
    

提交回复
热议问题