0

I'm not so talented with pointers. My function returns only the address and not the word itself.

 char* randstring(){
  char words[20];
  FILE *fp;
  int i = 0, j =0, ran = 0;
  srand(time(NULL));
  fp = fopen("text.txt", "r");

  //get size of the file
  for(; fgets(words , sizeof(words), fp); j++);

  ran = rand() % 10;
  rewind(fp);
  for( i = ran; i < j ; i++){
    fgets(words, sizeof(words), fp);
  }
  return words;
}

The goal of this function is to return a list of words from a text file, after that, I write in a File. Where exactly is the error with my pointer?

Eby Jacob
  • 1,418
  • 1
  • 10
  • 28
HQ189
  • 37
  • 3
  • 2
    `words` is locally scoped. Once it leaves scope, that data is garbage. You need to allocate it on the heap with `malloc` if you want the data to survive leaving scope. – Christian Gibbons May 09 '18 at 21:09
  • so do you mean like words = malloc(sizeof(char))? Thanks for the fast answer – HQ189 May 09 '18 at 21:15
  • 2
    @ChristianGibbons: Or, they need to pass the target buffer as an argument to the function. – John Bode May 09 '18 at 21:15
  • @HQ189 you would want the argument to malloc to be be the size of the buffer. In your given example you have an array of 20 chars, so you'd similarly want to tell malloc that your buffer will hold 20 chars: `malloc(20 * sizeof(char))` (note that `sizeof(char)` is redundant as a char is always 1 byte). – Christian Gibbons May 09 '18 at 21:19
  • Wait, you want to read and store an *array* of words? Because right now you're only storing a single word (the last word read from the stream). If your file contains 3 words and you want to save all 3 of them, then you'll need to create an array *of arrays* of `char`. – John Bode May 09 '18 at 21:22
  • @JohnBode not exactly store, after that i want to write those choosen words in a new file – HQ189 May 09 '18 at 21:25

0 Answers0