0

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?

Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102
  • 2
    Have you checked the file pointer returned by `fopen` to make sure it isn't NULL? Assuming `arr` contains 3 two-character long strings, that's the only thing I can think of that would cause `fputs` to barf. – John Bode Aug 31 '11 at 15:01
  • @John Bode please put it in an answer so i can accept it. I didn't think of missing permissions on the file at all. – Cobra_Fast Aug 31 '11 at 15:05

5 Answers5

2

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1
  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

Drakosha
  • 11,925
  • 4
  • 39
  • 52
0

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

Arun
  • 2,493
  • 15
  • 12
0

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.

Cajunluke
  • 3,103
  • 28
  • 28
0

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

niko
  • 9,285
  • 27
  • 84
  • 131
  • Oppz sorry I got his question wrong I later on understood well I was sorta thinking he wants a character sorry for the wrong answer! well if my answer totally wrong? – niko Aug 31 '11 at 15:26
  • okay im changing my code well I dont know that you can use 2 dimensional array in that way so i thought it might be wrong – niko Aug 31 '11 at 15:27