動的配列に関する宿題があるので、単純なプログラムでそれがどのように機能するかを理解しようとしていました。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int cnt,i=0;
char temp[1001];
char *obj[5];
scanf("%d",cnt);
while(i<cnt){
scanf("%s",temp);
obj[i]=malloc(sizeof(char)*(strlen(temp)+1));
obj[i]=temp;
printf("%s\n",obj[i]);
printf("%d\n",i);
i++;
}
return 0;
}
「cnt」が5になると、stdinから読み取ると、終了条件は満たされますが、プログラムは永久に実行されます。しかし、「cnt」を5に等しくすると、プログラムの最初に(scanfを使用するのではなく)割り当てることで、プログラムは正常に動作します。この理由は何でしょうか?