c - C-堆栈实现-malloc问题

标签 c struct compiler-errors declaration definition

我正在尝试使用堆栈实现方括号余额检查器,而我似乎无法摆脱这个问题
错误

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

 
这是代码:
balance.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;
}
stack.c
        #include "stack.h"
        #include "fatal.h"
        #include <stdlib.h>

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

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

.............
.............
stack.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 */
我只列出了引起问题的重要部分。因为一切似乎都正确,这没有任何意义:/

最佳答案

在带主翻译单元

#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中计算此类对象的大小
S = malloc(sizeof(*S));
您需要从头"stack.c"中的"stack.h"中移动结构定义。
请注意,根据C标准,函数main应该声明为
int main( void )
代替
void main()

关于c - C-堆栈实现-malloc问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65312410/

相关文章:

c - C中将字符串赋值给字符指针的解释

c - 在以下情况下如何获取数组的大小 :

c - 给一个整型数组赋值会改变另一个整型数组

Swift - 如何在结构中初始化数组?

json - 如何使用 goreq 将 json 转换为结构?

c - "two or more data types in declaration specifiers "错误是什么意思?

c - MinGW 未定义对 malloc、free、sprintf、_beginthreadex 的引用

c - 对于 HTTP 1.0,epoll 仍然比阻塞监听更高效吗?

C++ 错误 : expected identifier before ‘int’

typescript 输出属性错误