简体   繁体   中英

How split a string in c with comma

I created a function to split a string with comma.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char splitted_line[8][50];

void split(char *line){
    
    printf("line 9\n");
    char *part = strtok(line, ",");
    printf("line 11\n");

    for(int i=1; i<8; i++){
        strcpy(splitted_line[i], part);
        printf("%s\n", splitted_line[i]);
        part = strtok(NULL, ",");
    }
}

int main(){
    char *line = "123,456,789";
    split(line);
    return 0;   
}

but the result after running is:

line 9
Segmentation fault (core dumped)

it seems the problem is in char *part = strtok(line, ","); but I don't know what's that.

strtok() will modify passed original string directly.

You must not modify string literals.

char *line = "123,456,789";

should be modifyable array

char line[] = "123,456,789";

Also don't forget to check if part is not NULL before doing strcpy(splitted_line[i], part); .

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