我试图在 C 中创建一种可以接受大多数原始类型的类型。我是 C 新手,不太了解结构。我的错误发生在第 10 行(main.c),如果删除第 10 行(也是 main.c),它也会发生在第 11 行。如果有人有想法/指示,我将不胜感激!非常感谢!
主文件:
#include <stdio.h>
#include "modularType.h"
int main()
{
int data = 1;
PyType object = createPyObjectInt(data);
printf("Type of data: %d\n", object->typeOfData);
printf("Value of data: %d\n", object->intData);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
模块化类型.h:
typedef struct pytype *PyType;
PyType createPyObjectEmpty(void);
PyType createPyObjectInt(int data);
void setDataInt(PyType, int data);
void setDataIntStar(PyType, int* data);
void freeMyType(PyType);
void freeCharStar(PyType);
void freeIntStar(PyType);
void freeFloatStar(PyType);
Run Code Online (Sandbox Code Playgroud)
模块化类型.c:
#include <stdlib.h>
#include <stdio.h>
#ifndef NEW_TYPE
#define NEW_TYPE
#include "modularType.h"
typedef enum
{
NO_DATA,
REG_CHAR,
CHAR_STAR,
REG_INT,
INT_STAR,
REG_FLOAT,
FLOAT_STAR,
}types;
struct pytype
{
//The number of data types i can hold here
unsigned char typeOfData: 3;
union
{
char charData;
char* charStarData;
int intData;
int* intStarData;
float floatData;
float* floatStarData;
}
};
PyType createPyObjectEmpty(void)
{
PyType object;
object = malloc(sizeof(*object));
object->typeOfData = NO_DATA;
return object;
}
PyType createPyObjectInt(int data)
{
PyType object;
object = malloc(sizeof(*object));
object->intData = data;
object->typeOfData = REG_INT;
return object;
}
void setDataInt(PyType object, int data)
{
object->intData = data;
object->typeOfData = REG_INT;
}
void setDataIntStar(PyType object, int* data)
{
object->intStarData = data;
object->typeOfData = INT_STAR;
}
#endif
Run Code Online (Sandbox Code Playgroud)
作为旁注,我的编译命令 (gcc -Wall -std=c99 -o modType main.c modulesType.c) 产生以下警告:moduleType.c:35:1: warning: no semicolon at end of struct or union。我认为我已经正确格式化了结构,但我也看到人们将结构定义如下:
typedef struct pytype
{
//code here
}PyType;
Run Code Online (Sandbox Code Playgroud)
这是更好的方法还是我做的很好?
头文件中的结构体定义不完整,因此您不能在代码中引用任何结构体成员。编译器抱怨它根本不知道任何结构成员。
一个不完整的结构定义是,你不提供成员实施的列表。这样的定义允许您操作指向此类结构的指针,但不能访问任何成员,因为它们没有明确定义,并且编译器需要知道它们的类型和从结构开头的偏移量以生成相应的代码。
也不是 typedefPyType隐藏了指向 a 的指针struct pytype。将指针隐藏在 typedef 后面很容易出错,导致程序员和读者混淆代码。