簡體   English   中英

通過使用指針來實現堆棧

[英]Implement a stack by using a pointer to pointer

我正在實現一個使用雙指針進行練習的小程序,這是主程序:

#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 */ 
}

我已經實現了推功能,看來還可以。 但是,彈出窗口僅返回最后一個元素,然后返回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;
}   

您的push和pop函數過於復雜且完全錯誤:

你要這個:

void push(int **sp, int value) {
  **sp = value;   // put value onto top of the stack
  (*sp)++;        // increment stack pointer
}

int pop(int **sp) {
  (*sp)--;        // decrement stack pointer
  return **sp;    // return value which is on nthe op of the stack
}

您輸入的錯誤代碼帶有注釋說明:

void push(int **sp, int value) {
  int *pt; 
  pt=&value; // here you put the pointer to the local variable value
             // into pt, but local variables disappear as soon
             // as the function has finished

  //  the printf is the only thing one more or less correct
  //  but you could just print directly 'value' like this:
  //    printf("Pushed value is %d\r\n", value);
  //
  printf("Push value is is %d\r\n", *pt);

  sp = &pt;  // this only assigns the pointer to the local variable pt to 
             // the local variable sp

  ++(*pt);   // here you increment actually the local variable
             // value which is pointless 
}

順便說一句:盡管在調試過程中可能會有所幫助,但不必將整個堆棧初始化為零。 因此,您可以像這樣編寫堆棧的聲明:

int stack[10];  // no initialisation necessary

為您練習:

說明不需要將堆棧的所有元素初始化為零的確切原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM