これは基本的な説明です。 segfaultは、アクセス権のないメモリを使用していることを意味します。
int main()
{
char* a; // Create a pointer (a pointer can only contains an address (int size)
a[200]; // Trying to access to the byt 200 of your pointer but basicaly do nothing. You are suppose to have a segfault here
fgets(a, 200, stdin); // store your stdin into &a (you may have a segfault here too)
return 0;
};
多くのことによっては、失敗することがあります。時には失敗することもあります。しかし、あなたはここで何か間違っている。 これを修正する方法があります。まず
#include <stdio.h> /* for stdin */
#include <stdlib.h> /* for malloc(3) */
#include <string.h> /* for strlen(3) */
#include <unistd.h> /* for write(2) */
int main()
{
char str[200];
fgets(str, sizeof str, stdin);
write(1, str, strlen(str)); /* you can receive less than the 200 chars */
return (0);
}
CHARまたはあなたがポインタ
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
const size_t sz = 200;
char* str;
str = malloc(sz);
fgets(str, sz, stdin);
write(1, str, strlen(str));
}
しかし、いずれにせよを使用して保存しておきたい場合は、単純な配列を使用して、
C.
内のポインタとメモリに関する知識の欠如から、あなたのミスの結果それと幸運、
'a [200];'原因[未定義の動作](http://stackoverflow.com/a/4105123/1505939) –
それについての謎はありません。それは問題である基本的なCを学ぶことに失敗しています。 'char * a; a [200]; ' - >' char a [200] 'と' char * b; b [200]; ' - >' char b [200] ' – kaylum
@ M.Mしかし、なぜそれは未定義の振る舞いですか? –