繁体   English   中英

c中相同结构的不同typedef

[英]different typedef of the same struct in c

在SequenceStack.h中,我有以下代码

#ifndef SEQUENCESTACK_H
#define SEQUENCESTACK_H

#ifndef DATASTRUCTURE_MAZE_H
typedef int SElemType_Sq;
#endif

typedef struct {
    SElemType_Sq *base;
    SElemType_Sq *top;
    int stacksize;
}SqStack;

在SequenceStack.c中,我有

#include "SequenceStack.h"

定义一个堆栈。

在另一个我想使用堆栈但要更改elemtype的程序中。

所以在Maze.h中

#ifndef DATASTRUCTURE_MAZE_H
#define DATASTRUCTURE_MAZE_H

typedef struct {
    int x;
    int y;
}PosType;

typedef struct {
    int ord;
    PosType seat;
    int di;
}SElemType_Sq;

#include "SequenceStack.h"

仅在调试器中更改的SqStack int ord会受到影响。

如果我将SequenceStack.h更改为

#ifndef SEQUENCESTACK_H
#define SEQUENCESTACK_H

typedef struct {
    int x;
    int y;
}PosType;

typedef struct {
    int ord;
    PosType seat;
    int di;
}SElemType_Sq;

typedef struct {
    SElemType_Sq *base;
    SElemType_Sq *top;
    int stacksize;
}SqStack;

在Maze.h中什么也没放,一切正常。

我想知道出了什么问题以及为什么#ifndef无法正常工作。 我可以给出源代码。

在C(和C ++)中, #include是一种非常原始的机制,它只是在实际编译之前对包含文件中的文本进行“复制粘贴”。

因此,这里发生的是,您使用int*指针编译了SequenceStack.c 函数中的代码使用该类型。

然后,您传递这些与之不匹配的函数参数。 因此,难怪事情无法正常进行。

如果要使用带有指针的“通用”堆栈,建议您使用void*指针指向SequenceStack中的元素。 根据您的完整代码,例如您需要复制/重新分配元素,您可能必须将元素的大小添加到SqStack

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM