Sums
Sums

Reputation: 33

How can I return an char array from a function using malloc

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 ?

Upvotes: 2

Views: 1739

Answers (3)

Sums
Sums

Reputation: 33

Thanks you all for your answers ! I managed to make it work.

I changed my function return type to char** I allocated memory dynamically to my array like this: arr = (char **)malloc(words*sizeof(char));

and then it worked in my main when I delcared char **arr = toArray("file.txt");

Upvotes: 0

Shubham Agrawal
Shubham Agrawal

Reputation: 619

Your array is local, we need to declare it dynamically. Please try below sample code.

char **arr = NULL;
arr = (char**)malloc(words*sizeof(char*))
/* then use it */
return arr;

Upvotes: 1

SQL Police
SQL Police

Reputation: 4196

Your code:

 char *arr = toArray("file.txt");

In this case, arr is a string, and not an array of strings! Therefore, arr[0] is just a single char, and not a string. And a single char is basically treated like an int.

Upvotes: -1

Related Questions