このプログラムを実行すると、ファーストネームを入力することができ、セグメンテーション違反が発生します。ループ内のファイルに書き込むが、セグメンテーションフォールトを取得する
なぜこのようなことが起こるのか、それを取り除く方法はわかりません。
#include <stdio.h>
int main (void)
{
FILE *fp;
fp = fopen("list.txt","a+");
if (fp == NULL){
printf("File list.txt could not be opened.");
}
for(int i=0;i<3;i++){
char *name;
char *str;
char *sta;
printf("Please enter your name: ");
scanf("%s",name);
printf("Please enter your street: ");
scanf("%s",str);
printf("Please enter your state: ");
scanf("%s",sta);
fprintf(fp,"%s,%s,%s\n",name,str,sta);
}
fclose(fp);
}
最初の質問:デバッガは何を言っていますか? – tadman
ヒント: 'char * name'は' scanf'ですぐに使用できる文字バッファではありません。初期化されていません。スペースを割り当てられていません。それは爆発するだろう。 – tadman
scanfの[documentation](http://www.cplusplus.com/reference/cstdio/scanf/)には、「...(追加の引数)」と書かれています フォーマット文字列に応じて、関数は追加のシーケンス引数には、割り当てられた記憶域へのポインタを含む** **抽出された文字の解釈が適切な型で格納されている ' '(emphasis mine) – Les