found code

char string[]= "abc/qwe/jkh"; char *array[10]; int i=0; array[i] = strtok(string,"/"); while(array[i]!=NULL) { array[++i] = strtok(NULL,"/"); } 

And I set myself to make it more universal ie add dynamic memory allocation.

 #include <stdio.h> #include <string.h> char *string = "Value1,123,Value2,456,Value3,789,"; // запятая в конце необходима char **array_of_strings = NULL; // указатель на указатель строк int i = 0; long comma_counter = 0; int eachLine = 0; // считаем количество запятых, чтобы понять сколько нам нужно памяти for (i = 0; i < strlen(string); i++) { if (string[i] == ',') { comma_counter++; } } printf("Commas counted: %d\n", (int)comma_counter); array_of_strings = malloc(comma_counter * sizeof(char*)); // выделяем столько сколько насчитали if (array_of_strings == NULL) { printf("Memory allocation failed!"); exit(1); } 

And here is the first problem. The strok returns a pointer, and I need to write it to array_of_strings position 0.

How to write a string in array_of_strings [0]?

 ---> = strtok(string, ","); --->printf("%s\n", array_of_strings[eachLine]); --->while(*array_of_strings) // дальше надо делать снова вызов выделения памяти --->{ ---> array_of_strings = malloc(); ---> array_of_strings[++i] = strtok(NULL, ","); ---> array_of_strings++; --->} // ну а это будущий вывод строк на экран for (i = 0; i < comma_counter; i++) { printf("%s\n", array_of_strings[i]); } 

    1 answer 1

    An example of line breaks is here . I often use this resource. Something could be:

     char string[] = "Value1,123,Value2,456,Value3,789,"; int comma_counter=6; char *pCh; char **array_of_strings=(char**)malloc(sizeof(pCh)*comma_counter); //переменная string изменится int k=0; char * pch= strtok(string, ","); while(pch!=NULL) { array_of_strings[k] = (char*)malloc(strlen(pch)*sizeof(char)+1); if (array_of_strings[k]==NULL) exit (1); strcpy(array_of_strings[k], pch); pch = strtok (NULL, ","); k++; if(k==comma_counter) pch=NULL; } printf ("%s \n %s", array_of_strings[0],array_of_strings[comma_counter-1]); //не забывайте освобождать память for(int i=0;i<comma_counter;++i) { free(array_of_strings[i]); } free(array_of_strings); 
    • one
      Or you can call an existing strdup - avp
    • It falls right here char * pch = strtok (string, ","); If you change the char * string; on char * string [] then on this line does not fall, falls further. - GarfieldCat
    • @GarfieldCat Forgot to initially add the line pch = strtok (NULL, ",") ;. Try to determine the string, as I have in the code. - MindCleaner
    • @GarfieldCat A little mistake. More corrected. - MindCleaner
    • @MindCleaner Yes, but it still falls. - GarfieldCat