fscanf not reading strings into array

时间:2016-02-03 02:47:28

标签: c

Why doesn't this main print anything? It should print the first word in the file.

int main(int argc, char *argv[])
{
  FILE *file = fopen(argv[1], "r");
  int n = atoi(argv[2]);

  char **words = new char*[n];
  for(int i = 0; i < n; i++)
    {
      fscanf(file, "%s ", words[i]);
    }
  cout << words[0] << endl;
}

2 个答案:

答案 0 :(得分:2)

words[i] is a pointer that points to a random memory location. Make sure to make it point to allocated memory.

//Now words[i] points to the 1000 bytes allocated with the new keyword
words[i] = new char[1000];
//fscan will write the input to those bytes
fscanf(file, "%s ", words[i]);

答案 1 :(得分:2)

char **words = new char*[n]; will allocate a buffer to hold n pointers to char, words is just a pointer to an array of pointers. You need allocate enough memory for words[i](the pointer to ) to hold the string:

for (i=0; i < n; ++i ) {
    words[i] = new char[your_max_string_len];
}

Optionally you can use getline extension of GNU(if you use gcc) to do what you want:

size_t len = 0;
ssize_t read;
read = getline(&words[i], &len, stdin);
...
free(words[i]);

Actually, there is no magic in this function, it just does the memory allocation under the hood to save yours, and it's your responsibility to free it.