getline()関数については、文字列にメモリスペースを割り当てるために2つの方法を試しましたが、最初の方法は機能し、2番目の方法は機能しません。2番目が機能しない理由を誰かが説明できますか?
最初の1つ
#include <stdio.h>
int main()
{
int bytes_read;
int nbytes = 100;
char *my_string;
puts ("Please enter a line of text.");
/* These 2 lines are the heart of the program. */
my_string = (char *) malloc (nbytes + 1);
bytes_read = getline (&my_string, &nbytes, stdin);
if (bytes_read == -1)
{
puts ("ERROR!");
}
else
{
puts ("You typed:");
puts (my_string);
}
return 0;
}
2つ目:
#include <stdio.h>
int main()
{
int bytes_read;
int nbytes = 100;
char my_string[nbytes+1];
puts ("Please enter a line of text.");
/* These 2 lines are the heart of the program. */
bytes_read = getline (&my_string, &nbytes, stdin);
if (bytes_read == -1)
{
puts ("ERROR!");
}
else
{
puts ("You typed:");
puts (my_string);
}
return 0;
}
2つ目はコンパイルできますが、実行すると次のようになります。
bash-3.2$ ./a.out
Please enter a line of text.
lsdfa
Bus error: 10
バスエラー:10
考えられる理由はわかりませんが、誰か助けてもらえますか?