This is an array stack program. Please help. (Question after code) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

This is an array stack program. Please help. (Question after code)

#include<stdio.h> void push(char element, char stack[], int *top, int stackSize){ if(*top == -1){ stack[stackSize - 1] = element; *top = stackSize - 1; } else if(*top == 0){ printf("The stack is already full. \n"); } else{ stack[(*top) - 1] = element; (*top)--; } } void pop(char stack[], int *top, int stackSize){ if(*top == -1){ printf("The stack is empty. \n"); } else{ printf("Element popped: %c \n", stack[(*top)]); // If the element popped was the last element in the stack // then set top to -1 to show that the stack is empty if((*top) == stackSize - 1){ (*top) = -1; } else{ (*top)++; } } } int main() { int stackSize = 4; char stack[stackSize]; // A negative index shows that the stack is empty int top = -1; push('a', stack, &top, stackSize); printf("Element on top: %c\n", stack[top]); push('b',stack, &top, stackSize); printf("Element on top: %c\n", stack[top]); pop(stack, &top, stackSize); printf("Element on top: %c\n", stack[top]); pop(stack, &top, stackSize); printf("Top: %d\n", top); pop(stack, &top, stackSize); return 0; } Here, we add or remove elements in the array stack[] in functions push and pop. How come the the values updated in those functions get updated in the main aswell without using any pointer array or returning anything? it's not even a global variable..

21st Oct 2020, 6:17 AM
Thashreef Mohammed
Thashreef Mohammed - avatar
1 Answer
+ 1
hey Mohammed, array don't get copied when we passing through a function unlike variables which get copied. An alias is created for the same array which is passing.So the change in the function could get reflected in main function.
15th Sep 2021, 8:10 AM
Praveen Kumar Patini
Praveen Kumar Patini - avatar