Three level indirection char pointer in C causes a segment fault -
i got segment fault error @ line comments contains lots of equals signs below.
the function below str_spit, wrote because want split string using specific char, comma etc.
please help.
int str_split(char *a_str, const char delim, char *** result) { int word_length = 0; int cur_cursor = 0; int last_cursor = -1; int e_count = 0; *result = (char **)malloc(6 * sizeof(char *)); char *char_element_pos = a_str; while (*char_element_pos != '\0') { if (*char_element_pos == delim) { char *temp_word = malloc((word_length + 1) * sizeof(char)); int = 0; (i = 0; < word_length; i++) { temp_word[i] = a_str[last_cursor + 1 + i]; } temp_word[word_length] = '\0'; // *result[e_count] = temp_word;//==============this line goes wrong :( e_count++; last_cursor = cur_cursor; word_length = 0; } else { word_length++; } cur_cursor++; char_element_pos++; } char *temp_word = (char *) malloc((word_length + 1) * sizeof(char)); int = 0; (i = 0; < word_length; i++) { temp_word[i] = a_str[last_cursor + 1 + i]; } temp_word[word_length] = '\0'; *result[e_count] = temp_word; return e_count + 1; } //this caller function==================== int teststr_split() { char delim = ','; char *teststr; teststr = (char *) "abc,cde,fgh,klj,asdfasd,3234,adfk,ad9"; char **result; int length = str_split(teststr, delim, &result); if (length < 0) { printf("allocate memroy failed ,error code is:%d", length); exit(-1); } free(result); return 0; }
i think mean
( *result )[e_count] = temp_word;// instead of
*result[e_count] = temp_word;// these 2 expressions equivalent when e_count equal 0.:)
Comments
Post a Comment