2012-07-18 50 views
0

以下是我在編寫程序時遇到的一個問題,其中我提示用戶輸入儘可能多的值,然後打印輸入的每個整數的結果。無法使用動態內存分配來存儲運行時數組

我被建議在我的最後一個問題How to test my program against an input test case file中使用https://stackoverflow.com/users/319824/gcc的動態memeory分配。


我的代碼如下:

#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試圖突破,程序不會響應。我不能使用動態內存分配來解決這些問題嗎?如果是的話,我在哪裏錯了?

+0

您的意思是CTRL + C或CTRL + Z? – Rohan 2012-07-18 09:35:59

+0

CTRL + Z在Windows上結束輸入,並將進程置於Linux上的後臺。每當我在兩者之間切換時,我都會發現我的成本。 – 2012-07-18 09:36:44

+0

@SteveJessop Windows在CTRL + D上做了什麼? – 2012-07-18 09:42:05

回答

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

如果您發送CTRL + Z到你的程序,scanf返回EOF,這是一個負數,而不是0,所以contition計算爲true,你在無限循環是。測試

while(scanf("%d",&coins) > 0) 
+0

是...我明白了。非常感謝 – OneMoreError 2012-07-18 09:38:54