I am implementing a small program to exercise with double pointers This is the main program:
#include <stdio.h>
#include "serial.h"
#include "stack.h"
int main(void) {
serial_init();
/* Array to hold stack entries */
int stack[10]={0};
/* Stack pointer */
int *stack_p = stack;
/* Code to call the functions */
push(&stack_p, 1);
push(&stack_p, 2);
push(&stack_p, 3);
push(&stack_p, 4);
printf("popped value: %d\r\n", pop(&stack_p));
printf("popped value: %d\r\n", pop(&stack_p));
printf("popped value: %d\r\n", pop(&stack_p));
printf("popped value: %d\r\n", pop(&stack_p));
}
void push(int **sp, int value) {
/* Implement it */
}
int pop(int **sp) {
/* Implement it */
}
I have implemented the push function it seems ok. However, the pop return back just the last element and then 10
void push(int **sp, int value) {
/* implemented it*/
int *pt;
pt=&value; // Store the value to the pointer
printf("Push value is is %d\r\n", *pt);
sp = &pt; // associate the pointer to the pointer of pointer
++(*pt);
}
int pop(int **sp) {
/* implemented it */
int value;
int *pt;
pt=&value;
sp = &pt;
*pt--;
return value;
}
(*pt)--. Otherwise, rightward operators generally bind tighter than leftward ones. Also, where is the pointerptgiven a value?pushis working? You never actually assignvalueto anything and&valueis the address of a temporary copy of the argument passed. The way to see if either operation is working is to inspect thestackarray inmain()- use a debugger it will be lot faster that posting questions.