:
This message was edited by tokoG at 2006-2-1 20:27:45
: I've been asking this question on my school msg board but all the replies I am getting sound like if there is no proper way of initialising an array for the infinite loop for example as follows;
:
: This programme I wrote below WORKS.
: But it doesn't end the programme properly instead I get this 'Access Violation' pop-up msg.
:
: If I want to make this programme infinite, how should I
properly initialise so that I can end the programme by ENTER and won't get the pop-up msg?
:
: Thanks!!
:
:
: #include<stdio.h>
:
: void main () {
:
: int numbers[]={0}, i=0, length;
:
: while (1) {
: printf("Input an integer and use -1 to end: ");
: scanf("%d", &numbers[i]);
: fflush(stdin);
: if (numbers[i] == -1)
: break;
: else
: i++;
:
: }
:
: length = i-1;
: printf("\n\nNumbers in reverse order\n");
: for (i=length; i >= 0; i--)
: printf("%d ", numbers[i]);
:
: getchar();
: }
:
:
I think a good way to achieve such a task would be to use a dynamic list, instead of resizing an array.
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s
{
int intvalue;
struct node_s *next;
} NODE;
typedef NODE *STACK;
void push(STACK *stackp,int i);
int pop(STACK *stackp);
void push(STACK *stackp,int i)
{
NODE *newnode;
if ((newnode=(NODE *) malloc(sizeof (NODE)))!=NULL)
{
newnode->intvalue=i;
newnode->next=*stackp;
*stackp=newnode;
}
}
int pop(STACK *stackp)
{
int i;
NODE *p;
p=*stackp;
*stackp=p->next;
i=p->intvalue;
free(p);
return i;
}
int main(void)
{
int n;
STACK stack=NULL;
while (1)
{
printf("Input an integer and use -1 to end: ");
scanf("%d",&n);
if (n==-1) break;
else push(&stack,n);
}
while (stack!=NULL) printf("%d\n",pop(&stack));
return 0;
}
Steph