fwrite
機能を使用してテキストファイルに文章を書きたいと思います。 - 配列内の最初のオブジェクトへのポインタ書き込まれる 文字の配列をテキストファイルにコピー
fwrite(const void *restrict buffer, size_t size, size_t count, FILE *restrict stream)
- バッファ:だから私は、関数の引数としてこれらを持っている必要がありますHow to dynamically allocate memory space for a string and get that string from user?が、それは無駄に悪い習慣である、言ったように、出力ストリームへのポインタ
から
私の考えがある:それはEOF
malloc
を使用して、その配列がどんどん大きく作る- と
realloc
残念ながら私は問題に遭遇しました。私はコードをビルドして実行するたびに、それは私に、このエラーを与える:
has stopped working
HERESに私のコード:
あなたはsentence = realloc(sentence, size)
を記述する必要が #include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t index=0,size=1;
char ch;
FILE *fptr;
fptr=fopen("E:\\Textsample.txt","w");
/////////////////Checking///////////////
if(fptr==NULL)
{
free(fptr);
puts("Error occured!\n");
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
char *sentence =(char*) malloc(sizeof(char)) ;
puts("Plaese write :\n");
while((ch=getchar()) != EOF)
{
sentence[index]=ch;
index++;
size++;
realloc(sentence,size);
/////////////////Checking///////////////
if(sentence==NULL)
{
printf("Error Occured!\n");
free(sentence);
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
}
//Copying sentnce(s) to the text file.
fwrite(sentence,sizeof sentence[0],index,fptr);
free(sentence);
free(fptr);
return 0;
}
Nitpick:チェックコードでNULL ptrを解放する必要はありません。 –
"動作を停止しました"?何?たぶん、デバッガで実行し、それがクラッシュする行を参照してください。 –
@ HennoBrandsma-再割り当てに失敗したらどうしますか? –