Daemon-
Daemon-

Reputation: 5

Scan to Array of Strings

Segmentation fault (core dumped)

In C, I initialized an array of strings, like this:

char* strings[20];

then tried to fscanf a bunch of stuff.

for(int i = 0; i<20; i++){
  fscanf(file, "%s", strings[i]);
}

although there is more to the program, I am sure that this is the part causing a segmentation fault. A run using gdb stated that the error was in file vfscanf, so I think this is related.

Upvotes: 0

Views: 5975

Answers (3)

Kaizhe Huang
Kaizhe Huang

Reputation: 1006

After your declaration

char* strings[20];  // This is an array of pointer of type char *

You will need to allocate memory for each pointer before you can read into them from the file.

for(int i = 0; i<20; i++){
  strings[i] = malloc(some_size * sizeof(char)); // allocate memory for each pointer first.
  fscanf(file, "%s", strings[i]);
}

Upvotes: 5

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

Note that if you have a sufficiently modern POSIX-compliant version of scanf() (check your system manual), you can use:

for (int i = 0; i < 20; i++)
{
    if (fscanf(file, "%ms", &strings[i]) != 1)
        …report error and break/return…
}

With the %ms conversion specification, scanf() will use malloc() to allocate the appropriate amount of memory for the string it reads. Don't forget to free() the memory when you're done with it.

Note that Mac OS X (10.9.5 Mavericks) does not have a sufficiently modern version of scanf(). Linux (as found in Ubuntu 14.04, for example), does.

Upvotes: 1

chux
chux

Reputation: 153338

char* strings[20]; does not initialize an "array of string".

Instead strings is an array of 20 char * pointers. A strings in C is array of char up to an including the trailing '\0'. So far, the array Strings[] has indeterminate values and none of the elements certainly point to a string.

By assigning those 20 pointers to various strings, you will have an "array of strings".

// Assign 0 (or NULL) to each pointer.
char* strings[20] = { 0 };

for(int i = 0; i<20; i++){
  char buffer[100];
  if (fscanf(file, "%99s", buffer) != 1) {
    break;
  }
  strings[i] = strdup(buffer);  
  // or
  size_t len = strlen(buffer) + 1;
  strings[i] = memcpy(malloc(len), buffer, len);  // error check omitted
}

Upvotes: 1

Related Questions