Search code examples
arrayscstringstack

printf not printing value of a character array in C


The printf statement within the pop function isn't printing anything except a blank character (space). I tried to print the indexes of the array passed in the pop function but the same thing is happening. I can't seem to figure out why, can someone please help me?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char stack[400] = "";
int top = -1;

void push(char arr[], int *top, char val) {
    *top = *top + 1;
    arr[*top] = val;
    //printf("%d", *top);
} 

char pop(char arr[], int *top) {
    char temp;
    printf("\n%s\n", arr[0]);
    temp = arr[*top];
    *top = *top - 1;
    return temp;
}

int main() {
    push(stack, &top, 'a');
    push(stack, &top, 'b');
    push(stack, &top, 'c');
    //printf("%s", stack);
    pop(stack, &top);
    //printf("\n%s", *val);
    return 0;
}

Solution

  • If you want to print individual stack elements, you can use %d or %c like this:

    char val = pop(stack, &top);
    printf("stack top was %c (ASCII %d)\n", val, val);
    

    If you want to print the whole stack as a string, you can use:

    printf("stack: %.*s\n", top + 1, stack);
    

    Note that since stack and top are passed as arguments, there is no need to make them global variables.

    Here is a modified version:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define STACK_DEPTH  400
    
    void push(char arr[], int *top, char val) {
        if (top < STACK_DEPTH - 1) {
            *top = *top + 1;
            arr[*top] = val;
        } else {
            fprintf(stderr, "stack full for '%c'\n", val);
        }
    } 
    
    char pop(char arr[], int *top) {
        if (top >= 0) {
            char temp = arr[*top];
            *top = *top - 1;
            return temp;
        } else {
            fprintf(stderr, "stack empty\n");
            return 0;
        }
    }
    
    int main() {
        char stack[STACK_DEPTH] = "";
        int top = -1;
    
        push(stack, &top, 'a');
        push(stack, &top, 'b');
        push(stack, &top, 'c');
        printf("stack contents: %.*s\n", top + 1, stack);
    
        char val = pop(stack, &top);
        printf("stack top was %c (ASCII %d)\n", val, val);
        return 0;
    }