OneMoreError
OneMoreError

Reputation: 7728

Unable to use dynamic memory allocation to store runtime arrays

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 ?

Upvotes: 0

Views: 131

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183873

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)

Upvotes: 5

Related Questions