-
split string function
hello. i am trying to make a split function that takes in a string and a delimiter, and returns a array of strings that have been separated by the delimiter.
here is my code so far:
Code:
char * split(char string[], char * sep){
// char str[] = &string;
char * pch;
char * out[3];
int i=0;
printf ("h1\n");
pch = strtok (string," ,");
printf ("h2\n");
while (pch != NULL)
{
printf ("\"%s\"\n",pch);
out[i] = pch;
i++;
if(pch != NULL) pch = strtok (NULL, " ,");
}
//out[i] = '\0';
printf("h3 %s\n",out[0]);
return out;
}
int main(){
printf("start\n");
char * out = split(str, " ,");
printf("end\n");
printf ("out 1: %s\n",out[0]); // segmentation fault happens here
printf ("out 2: %s\n",out[1]);
printf ("out 3: %s\n",out[2]);
return 0;
}
the input i used is: "this, is, crazy"
i get a segmentation fault after the printf of "end"
-
listen to your compilers warnings.
Kurt
-
something to the effect of this:
Code:
database.c: In function ‘split’:
database.c:47: warning: return from incompatible pointer type
database.c:47: warning: function returns address of local variable
database.c: In function ‘test’:
database.c:70: error: incompatible types in assignment
database.c: In function ‘start_database’:
database.c:87: warning: excess elements in scalar initializer
database.c:87: warning: (near initialization for ‘row’)
-
is this file named 'database.c'? if so then post the full code.
it would be helpful to us if you commented or somehow let us know what lines are #47, 70, and 87.
edit: it looks like your trying to do something with the variable 'out'. however it isnt initialized.is a pointer to an array of three chars.
-
It's not that simple what you are trying to do. Right now I don't have the nerve to try to explain how to do that.
try this code.
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char ** split(char string[], int * num, char * sep) {
char * pch;
char ** out = 0;
int i = 0;
pch = strtok (string, sep );
while (pch != 0 ) {
out = realloc(out, ( i + 1 ) * sizeof( char * ));
out[i] = malloc( strlen(pch ) + 1 );
strcpy( out[i], pch );
++i;
pch = strtok (NULL, sep);
}
*num = i;
return out;
}
int main() {
char str[255] = "one, two, tree, four,five six";
int num = 0;
int i = 0;
char ** tokens = split( str, &num, " ,");
for( i = 0; i < num; ++i )
printf("%s\n", tokens[i] );
for( i = 0; i < num; ++i )
free( tokens[i] );
free(tokens);
}
Feel free to ask how it works.
Kurt
EDIT: proper error checking needs to be added.
-
thank you ZuK this works.
i love the versitilty of c.. but i have worked with python for so long, i forgot to appreciate c.
i would like to know how this works..
like the functions
realloc and free
-