Domanda

I am gathering data into a char[][] array, then let a user choose which of those string to write to a file. So I'm doing for example

char arr[3][3]; // assume there are three different two-char long strings in there
FILE* f = fopen("file", "w");
fputs(arr[1], f);
fclose(f);

Now the problem is, I'm getting a segfault on the fputs() call and I dont know why.

Any Ideas?

È stato utile?

Soluzione

Make sure the file pointer returned by fopen isn't NULL; assuming arr contains valid 0-terminated strings, that's the only other thing I can think of that would cause fputs to barf.

Altri suggerimenti

  1. fputs expects \0-terminated string. Make sure you add 0 in the end of the string that you supply there. Alternatively use fwrite.

  2. check that f != NULL after fopen

What is arr pointing to? I guess the problem is due to arr not being initialized.

The char array pointed to by arr[1] is probably not null-terminated. You should declare arr as char arr[3][4]; and fill the last column with '\0' (null) characters.

May be you should check for the value returned by the file pointer!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top