gpt4 book ai didi

c - 在 C 中为结构类型分配内存

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:51 25 4
gpt4 key购买 nike

我在我的程序中遇到一个问题,我定义了一个结构类型,但没有在标题中定义结构变量。

typedef struct 
{
int a;
int b;
int c;
Token d;
} Foo;

然后我想稍后在一个 .c 文件中使用这个结构 foo,它会中缀到后缀

#include "header"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>

int infix2postfix(char *infix, Arr arr)
{
struct Foo foo;
char szToken[MAX_TOKEN];
Stack stack = newStack();
infix = getToken(infix, szToken, MAX_TOKEN); //provides next token to be scanned by function.

... //push pop using switch case didn't post code for simplicity.
case...
push(stack, *foo.a);

...
case...
pop(stack);

...

goOut(arr, *foo.d); //goOut(function that populates and "arr" Array from printing.

}

所以当我在这里编译时我得到

error: storage size of ‘foo’ isn’t known struct Foo foo;

我已经尝试过 struct Foo *foo = malloc(sizeof foo); 来分配内存,但它弄乱了我的 push(stack, *foo.a);goOut(arr, *foo.d); 我该如何解决这个问题?我是否必须先在 infix2postfix 函数中分配内存,然后再声明一个结构变量?

最佳答案

您定义了一个 Foo 类型,它是一个无标记的 struct 类型。你可以有一个单独的 struct Foo { int anonymous;字符名称[MAX_NAME]; };Foo 类型完全无关。 (这对人类来说会很困惑,但编译器不会有问题。)

在你的函数中,你应该写:

int infix2postfix(char *infix, Arr arr) 
{
Foo foo;

关于c - 在 C 中为结构类型分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com