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 开发者_如何学Pythonare 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?
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.
fputs
expects\0
-terminated string. Make sure you add0
in the end of the string that you supply there. Alternatively usefwrite
.check that
f != NULL
afterfopen
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!
精彩评论