I am trying to write a function that reads a text file and puts every words of this text into an array with dynamic allocation so that this array is not over-sized.
I managed to write a working function that creates an array with every words (i.e arr[0] = "bla", arr[1] = "bla", ...) but I can't return this array, so i can use it in my main().
char* toArray(char *filename) {
int words = countWords(filename); // this function returns the number of words in the file
char *arr[words];
int cur_size = 0;
int i;
FILE *file;
file = fopen(filename, "r");
for(int i = 0; i < words; i++) {
fscanf(file, "%*s%n", &cur_size);
arr[i] = malloc( (cur_size+1) * sizeof(char));
}
fclose(file);
file = fopen(filename, "r");
for (i = 0; i < words; i++) {
fscanf(file, "%s", arr[i]);
printf("%s\n", arr[i]);
}
fclose(file);
return arr; // not sure if this is how i should return it
}
int main(int argc, char const *argv[]) {
char *arr = toArray("file.txt");
printf("%s", arr[0]);
return 0;
}
I expected
printf("%s", arr[0])
to print the first word of my file.
but instead i get this error : format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] printf("%s\n", arr[0]);
I guess i made a mistake in my function ?
arrdynamically, the arrayarritself is not allocated dynamically. Returning it will return a pointer to a local variable, a local variable which will cease to exist immediately once the function returns. What's more, you have an array of pointers, which will never be equal to the typechar *, but with dynamic allocation could be of the typechar **.arrlike this now :char *arr = malloc(numberOfChar*sizeof(char));but now i got issues with my elements allocation :arr[i] = malloc( (cur_size + 1) * sizeof(char))assignement makes integer from pointer without a cast i don't know why this happenschar *. And array can be seen as a pointer to its (first) element. So if you have an array ofchar *you need a pointer tochar *which turns out to be achar **. Now for how to allocate it, you're part-ways there with the code you show in your question.