简体   繁体   English

在C - 分割错误中使用分隔符拆分字符串

[英]Splitting string with delimiters in C - segmentation fault

I want to write a function that will split a string into a char array. 我想编写一个将字符串拆分为char数组的函数。 I know that the result array will ALWAYS have only two elements - servername and serverport. 我知道结果数组总是只有两个元素 - servername和serverport。 I wrote this, but it gives me "Segmentation fault" after compilation: 我写了这个,但它在编译后给了我“Segmentation fault”:

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

char* splitString(char stringToSplit[])
{
    int i = 0;
    char serverinfo[2];
    char *tmp;
    tmp = strtok(stringToSplit, ":");
    while (tmp != NULL)
    {
        serverinfo[i] = tmp;
        tmp = strtok(NULL, ":");
        i++;
    }
    return serverinfo;
}

int main(int argc, char **argv)
{
    char st[] = "servername:1234";
    char *tab = splitString(st);

    printf("%s\n", tab[0]);
    printf("%s\n", tab[1]);

    return 0;
}
char serverinfo[2];

allocates space for two char s, but you store char* s there, so make it 为两个char分配空间,但是你将char*存储在那里,所以制作它

char* serverinfo[2];

But you return it from the function, however, the local variable doesn't exist anymore after the function returned, so you need to malloc it 但是你从函数返回它,但是,函数返回后局部变量不再存在,所以你需要malloc

char **serverinfo = malloc(2*sizeof *serverinfo);

and declare the function as 并将该函数声明为

char **splitString(char stringToSplit[])

for the correct type. 为了正确的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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