2015-06-24 2 views
-4

Когда я выполняю его, функция не работает, почему?Новый программист здесь, что случилось с этой программой стека?

#include<stdio.h> 

struct stack{ 

int x[10]; 

int last; 
}; 

void init(struct stack *s) 
{ 

    s->last=0; 
} 

void insert(struct stack *s) 
    { 
     int a; 

     while(a!=0) 
     { 
     int i; 
     printf("Enter the value\n"); 

     scanf("%d",&i); 

     s->last++; 

     s->x[s->last]=i; 
     printf("%d",s->x[s->last]); 
     printf("enter 1 to continue 0 to exit\n"); 
     scanf("%d",&a); 

    } 
    } 

int main() 
{ 

    struct stack s; 

    int y,z; 

    printf("Trying out stacks\n"); 

    printf("\n______________\n"); 

    init(s); 

    insert(s); 

    return 0; 

} 
+3

Почему вам не кажется, что этот код работает? Какое у вас это есть? * Опишите проблему. * – David

+0

'int a;' -> 'int a = 1;', 's-> last = 0;' -> 's-> last = -1;', 'init (s); '->' init (&s); ',' insert (s); '->' insert (&s); ' – BLUEPIXY

ответ

2

В функции insert(), вы объявили

int a; 

, а затем без инициализации a вы делаете следующее,

while(a!=0) 

даст Undefined Behaviour.

Следующие строки могут приводит переполнение буфера,

s->last++; 
s->x[s->last]=i; // no restriction applied on last 

last может быть больше, чем 9, которые могут вызвать переполнение буфера, как x[10].

Смежные вопросы