0

以下は、ユーザーに必要な数の値を入力するように求めるプログラムを作成しているときに発生した問題であり、入力された各整数の結果を出力します。

最後の質問How to test my program against an input test case file でhttps://stackoverflow.com/users/319824/gccから動的メモリ割り当てを使用するよう提案されました 。


私のコードは次のとおりです。

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *next;
}*start;

void insertatend(int d)
{
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
n->data=d;
n->next=NULL;

if(start==NULL)
{
    start=n;
}

else
{
    struct node *tmp;
    for(tmp=start;tmp->next!=NULL;tmp=tmp->next);
    tmp->next=n;
}

}

int max(int  a,int b)
{
int c=(a>b)?a:b;
return c;
}

int maxCoins(int n)
{
int arr[n+1],i;
arr[0]=0;
arr[1]=1;
arr[2]=2;
arr[3]=3;

if(n>2)
{


for(i=3;i<=n;i++)
{
    int k= arr[(int)(i/2)]+arr[(int)(i/3)]+arr[(int)(i/4)];
    arr[i]=max(i,k);
}
}

 return arr[n];
}


int main(void)
{
int coins,i;
start=NULL;
struct node*p;

while(scanf("%d",&coins))
{
    insertatend(coins);
}

for(p=start;p!=NULL;p=p->next)
{
    printf("%d\n",p->data);
}

getchar();
return 0;
}

プログラムは正常に実行されます。任意の数の入力を行うことができます。CTRL + Z を押してブレークアウトしようとすると、プログラムは応答しません。このような問題に動的メモリ割り当てを使用できませんか? はいの場合、どこが間違っていますか?

4

1 に答える 1

5
while(scanf("%d",&coins))

プログラムに CTRL+Z を送信すると、0 ではなく負の数である がscanf返さEOFれるため、条件が true と評価され、無限ループに陥ります。テスト

while(scanf("%d",&coins) > 0)
于 2012-07-18T09:36:27.960 に答える