Breaking down string and storing it in array

前端 未结 2 771
小鲜肉
小鲜肉 2021-02-03 13:40

I want to break down a sentence and store each string in an array. Here is my code:

#include 
#include 

int main(void)
{
    int         


        
2条回答
  •  时光说笑
    2021-02-03 14:06

    It's because writablestring isn't writable at all. Attempting to write to a string literal is undefined behavior and strtok writes to it (that's right, strtok modifies its argument).

    To make it work, try:

    char writablestring[] = "The C Programming Language";
    

    There's also a C FAQ.

    Another problem is that you didn't allocate memory for your array of character pointers (so those pointers point to nothing).

    char* strArray[40]; /* Array of 40 char pointers, pointing to nothing. */
    

    Maybe try this ?

    /* Careful, strdup is nonstandard. */
    strArray[i] = strdup(token);
    
    /* Or this. */
    strArray[i] = malloc(strlen(token) + 1);
    strcpy(strArray[i], token);
    

提交回复
热议问题