I wrote a program to split a char array to a 2D array as the comments below the definition of the function states. However, I am receiving segmentation fault on this piece of code. Can some one help to find why?
The my_strlen(str) functions works the same way as the original strlen(str) function, and it works perfectly. And the length of the char array is limited, so I do not really worry about the efficiency in memory allocation.
char **my_str2vect(char *str) {
// Takes a string
// Allocates a new vector (array of string ended by a NULL),
// Splits apart the input string x at each space character
// Returns the newly allocated array of strings
// Any number of ' ','\t', and '\n's can separate words.
// I.e. "hello \t\t\n class,\nhow are you?" -> {"hello", "class,", "how", "are","you?", NULL}
int str_len = my_strlen(str);
char **output = malloc(sizeof(char *) * str_len); // Allocate a 2D array first.
if (**output) {
for (int a = 0; a < str_len; ++a) {
output[a] = malloc(sizeof(char) * str_len);
}
} else {
return NULL;
}
int i = 0;
int j = 0;
while (i < str_len) { // Put the characters into the 2D array.
int k = 0;
while ((str[i] == ' ' || str[i] == '\t' || str[i] == '\n') && i < str_len) {
++i;
}
while ((!(str[i] == ' ' || str[i] == '\t' || str[i] == '\n')) && i < str_len) {
output[j][k] = str[i];
++i;
++k;
}
output[j][k] = '\0';
++j;
}
output[j] = NULL;
return output;
}

my_strlen()?ifstatement;**outputis of typechar. You wantoutputinstead, which points to the allocated memory (which you probably wanted to check).