I'm trying to write some strings into a file. This compiles with no warnings, but when I run the a.out it segfaults. It does create the target file, though. I'm very new to C, so I apologize for my formatting and other shortcomings. Here is my code:
#include<stdio.h>
int main (void)
{
FILE *fp_out;
char str1[]="four score and seven years ago our";
char str2[]="fathers broughy forth on this continent,";
char str3[]="a new nation, concieved in Liberty and dedicated";
char str4[]="to the proposition that all men are created equal.";
fp_out=fopen("my_file", "w");
if(fp_out!=NULL)
{
fprintf(fp_out,"%s\n", str1[100]);
fprintf(fp_out,"%s\n", str2[100]);
fprintf(fp_out,"%s\n", str3[100]);
fprintf(fp_out,"%s\n", str4[100]);
fclose(fp_out);
}
else
printf("The file \"my_file\" couldn't be opened\n");
return 0;
}
str1[100]? NONE of your strings are anywhere close to 100 characters long, so you're acessing memory that hasn't been allocated. it shoul;d befprintf(fp_out, "%s\n", str1)strX[100]%sexpects a string variable or char pointer. You are passing a single characterstr1[100]for example, which is not a valid address. You want to passstr1.charwherefprintfexpects achar *. I.e. change it tostrXwithout the array-subscript ([100])