Question:
The algorithm should return a two-dimensional array with a space-separated string (the same split(" ") from Python).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Добавление char в конец массива char
void append(char* needed, char to_append) {
int length = strlen(needed);
needed[length] = to_append;
needed[length+1] = '\0';
}
char** split(char* input) {
int space_count = 0;
// Считаем пробелы
for (int i = 0; i < strlen(input); i++) {
if (input[i] == ' ') {
space_count++;
}
}
// Указатель на указатель на char.
char **splitted_input;
// Выделяем память под массивы char
splitted_input = (char**) malloc((space_count+1) * sizeof(*splitted_input));
// Хранилище для текущей строки (перед пробелом)
char word[100] = "";
int current = 0;
for (int i = 0; i < strlen(input); i++) {
if (input[i] == ' ') {
printf("NEW: [%d] = %s\n", current, word);
splitted_input[current] = word;
current++;
// Обнуляем весь массив
memset(word, 0, sizeof(word));
continue;
}
// Если не пробел, то добавляем в конец word новый символ
append(word, input[i]);
}
printf("NEW: [%d] = %s\n\n", current, word);
// Добавляем текущую строку
splitted_input[current] = word;
for (int i = 0; i < space_count+1; i++) {
printf("%s\n", splitted_input[i]);
}
// Еще не имею понятия, как здесь лучше освободить память splitted_input
return splitted_input;
}
int main() {
char input[20] = "hi everyone";
char** need = split(input);
return 0;
}
Outputs:
NEW: [0] = hi
NEW: [1] = everyone
everyone
everyone
I don't understand why splitted_input[0] is also equal to everyone
Answer:
Direct answer to the question: they both point to the same word
.
Another problem: an array with pointers to a local variable is returned from the function.
Solution. For splitted_input[current]
allocate memory for a new line where you copy the contents of word
:
splitted_input[current] = strdup(word);