0

The following is a problem which i encountered while writing a program where i prompt a user to input as many values as i want, and then i print the results for each integer thus entered.

I was suggested to use dynamic memeory allocation by https://stackoverflow.com/users/319824/gcc in my last question How to test my program against an input test case file.


My code is as follows:

#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;
}

The program runs successfully. I am able to give any number of inputs, and if I try to break out by pressing CTRL + Z ,the program does not respond. Can't I use dynamic memory allocation for problems like these ? And if yes, where am i wrong ?

3
  • CTRL+Z ends the input on Windows, and puts the process to the background on Linux. As I discover to my cost every time I switch between the two. Commented Jul 18, 2012 at 9:36
  • @SteveJessop What does Windows do on CTRL+D? Commented Jul 18, 2012 at 9:42
  • I don't think it does anything special. Commented Jul 18, 2012 at 9:43

1 Answer 1

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

If you send CTRL+Z to your programme, scanf returns EOF, which is a negative number and not 0, so the contition evaluates to true and you're in an infinite loop. Test

while(scanf("%d",&coins) > 0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.