簡體   English   中英

C - 堆棧實現 - malloc 問題

[英]C - Stack Implementation - malloc issue

我正在嘗試使用堆棧實現括號平衡檢查器,但我似乎無法擺脫這個

錯誤

tempCodeRunnerFile.c: In function ‘main’:
tempCodeRunnerFile.c:26:20: error: dereferencing pointer to incomplete type ‘struct StackRecord’
   26 |  S = malloc(sizeof(*S));
      |

 

這是代碼:

平衡.c

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

void main() 
{
    struct StackRecord *S;
    char str[500], c;
    int l, i;

    S = malloc(sizeof(*S));
    while (1) {
        .............
        .............
    
    return;
}

堆棧.c

        #include "stack.h"
        #include "fatal.h"
        #include <stdlib.h>

        #define EmptyTOS ( -1 )
        #define MinStackSize ( 5 )

        struct StackRecord
        {
            int Capacity;
            int TopOfStack;
            ElementType *Array;
        };

.............
.............

堆棧.h

typedef int ElementType;
/* START: fig3_45.txt */
        #ifndef _Stack_h
        #define _Stack_h

        struct StackRecord;
        typedef struct StackRecord *Stack;

        int IsEmpty( Stack S );
        int IsFull( Stack S );
        Stack CreateStack( int MaxElements );
        void DisposeStack( Stack S );
        void MakeEmpty( Stack S );
        void Push( ElementType X, Stack S );
        ElementType Top( Stack S );
        void Pop( Stack S );
        ElementType TopAndPop( Stack S );

        #endif  /* _Stack_h */

/* END */

我只放了導致問題的重要部分。 這是沒有意義的,因為一切似乎都是正確的:/

在帶有 main 的翻譯單元中

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

void main() 
{
    struct StackRecord *S;
    char str[500], c;
    int l, i;

    S = malloc(sizeof(*S));
    while (1) {
        .............
        .............
    
    return;
}

結構struct StackRecord的定義是未知的。 所以編譯器無法在算子sizeof中計算出這個類型的 object 的大小

S = malloc(sizeof(*S));

您需要從"stack.c"中的"stack.h"移動結構定義。

請注意,根據 C 標准,function 主要應聲明為

int main( void )

代替

void main()

為了分配struct StackRecord ,需要知道struct StackRecord的大小。 要使用sizeof運算符知道struct StackRecord的大小,需要定義struct StackRecord

問題是在當前翻譯單元的任何地方都找不到struct StackRecord的定義。 stack.c不參與編譯balance.c 。)

要解決此問題,請將struct StackRecord的定義從stack.c移至stack.h ,或讓stack.c提供一個struct StackRecord

暫無
暫無

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

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