I wanted to write a programm, that splits up a string into substrings. This should happen every time a certain character (for example a whitespace) is in the string.
The created substrings should be saved into an array of strings.
I know that i could have used the strchr function but at first i didn't want to use the string.h library.
I know, that the error is a segmentation fault even though codelite doesn't say so, because i ran it on another computer.
Hopefully someone can help me
 
 Code: Select all
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** splitString(char index, char* str)
{
  char** ret_str;
  char* buff_str;
  int loop_count1;
  int loop_count2;
  
  
  buff_str = (char*)malloc(sizeof(char) * strlen(str) + sizeof(char));
  ret_str = (char**)malloc(sizeof(char) * strlen(str) + sizeof(char));
  
  for(loop_count1 = 0; str[loop_count1] != '\0'; loop_count1++)
  {
    buff_str[loop_count1] = str[loop_count1];
    if(str[loop_count1] == index)
    {
      buff_str[loop_count1] = '\0';
    }
    if(loop_count1 == strlen(str))
    {
      buff_str[loop_count1 + 1] = '\0';
      break;
    }
  }
  
  int index_count = 0;
  
  for(loop_count2 = 0, loop_count1 = 0; loop_count1 <= strlen(str);
      loop_count2++, loop_count1++)
  {
    ret_str[index_count][loop_count2] = buff_str[loop_count1];
    
    if(buff_str[loop_count1] == '\0')
    {
      index_count++;
      loop_count2 = 0;
    }
    if(loop_count1 == strlen(str))
      ret_str[index_count][loop_count2 + 1] = '\0';
  }
  
  free(buff_str);
  return ret_str;
}
int main(int argc,char* argv[])
{
char a = ' ';
char* str = "Today is monday.";
char** str_arr= (char**)malloc(sizeof(char**));
str_arr = splitString(a, str);
printf("%s\n", str_arr[0]);
printf("%s\n", str_arr[1]);
printf("%s\n", str_arr[2]);
free(str_arr);
return 0;
}
 (in 20 mins or so)
 (in 20 mins or so)