I want to write a function that will split a string into a char array. I know that the result array will ALWAYS have only two elements – servername and serverport. I wrote this, but it gives me “Segmentation fault” after compilation:
#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;
}
allocates space for two
chars, but you storechar*s there, so make itBut you return it from the function, however, the local variable doesn’t exist anymore after the function returned, so you need to
mallocitand declare the function as
for the correct type.