Simple program in C

0

This I have removed from an old C book, the C book, I am learning c but I do not understand the last two results that this program gives that are a 100 and 99, I do not understand why it returns the vector in that way. Thank you very much.

#include <stdio.h>

static int buf[100];
static int length;

static void fillup(void){

    int i = 0;

    while(length < 100){
        buf[length++] = 0;
        i++;
        printf("%d, ",buf[i]);

    }   
}

int callable(){

    if(length == 0){
        fillup();
    }
    return(buf[length--]);          
}

int main(){

    int a;

    a = callable();

    printf("%d\n",a);

getchar();
return 0;
}
    
asked by repola 11.04.2018 в 17:24
source

1 answer

0

The following function pulls a value outside the array

int callable(){

    if(length == 0){
        fillup();
    }
    return(buf[length--]);// Dato basura, ademas de overflow
}

The solution if you want the last one returned, first decrease length, and then get the array data

int callable(){

    if(length == 0){
        fillup();
    }
    return(buf[--length]);
}

I hope I have understood your problem

    
answered by 11.04.2018 в 17:38