-5

Possible Duplicate:
Split string with delimiters in C

What's the best way to split a "," separated list into an array in C. I know how many things are in the list.

char list = "one,two,three,four";
int ENTServerAmount = 8;
char **ENTServer;
ENTServer = malloc(sizeof(char *) * ENTServerAmount);
*** Code that splits "list" into "ENTServer" ***

Also I'm not very good at allocating so let me know if my allocation statement is wrong.

Community
  • 1
  • 1
Bill
  • 1,237
  • 4
  • 21
  • 44

1 Answers1

3

strtok() is probably the function you are looking for.

char list[] = "one,two,three,four";
int ENTServerAmount = 8;
char **ENTServer;

char *tmp = strtok (str, ",");

int index = 0;
while (pch != NULL)
{
   ENTSever[index++] = tmp;
   tmp = strtok (NULL, ",");
}
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • 2
    -1 strtok is bad, it's not reentrant/multithreadsafe, destroys the string (string cannot be const/literal) and also ignores empty fields like ",,". Better you use sscanf with %n. – user411313 Jul 16 '12 at 19:32
  • 5
    @user411313 for the simple example explained by the OP, `strtok` is the right way to go. I will admit, that strtok has it's downfalls, but it is simple and easy to understand. as the OP seemed to be new to C, might as well introduce him to the simple stuff now, and the more complex stuff later. – Richard J. Ross III Jul 16 '12 at 19:47