Jam*_*yen 5 c struct compiler-errors incomplete-type
我正在为我的数据结构课程做作业,但我对 C 结构和 C 的总体经验很少。这是给我分配的 .h 文件:
#ifndef C101IntVec
#define C101IntVec
typedef struct IntVecNode* IntVec;
static const int intInitCap = 4;
int intTop(IntVec myVec);
int intData(IntVec myVec, int i);
int intSize(IntVec myVec);
int intCapacity(IntVec myVec);
IntVec intMakeEmptyVec(void);
void intVecPush(IntVec myVec, int newE);
void intVecPop(IntVec myVec);
#endif
Run Code Online (Sandbox Code Playgroud)
这是我所做的 .c 实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "intVec.h"
typedef struct IntVecNode {
int* data;
int sz; // Number of elements that contain data
int capacity; // How much is allocated to the array
} IntVecNode;
typedef struct IntVecNode* IntVec;
//static const int intInitCap = 4;
int intTop(IntVec myVec) {
return *myVec->data;
}
int intData(IntVec myVec, int i) {
return *(myVec->data + i);
}
int intSize(IntVec myVec) {
return myVec->sz;
}
int intCapacity(IntVec myVec) {
return myVec->capacity;
}
IntVec intMakeEmptyVec(void) {
IntVec newVec = malloc(sizeof(struct IntVecNode));
newVec->data = malloc(intInitCap * sizeof(int));
newVec->sz = 0;
newVec->capacity = intInitCap;
return newVec;
}
void intVecPush(IntVec myVec, int newE) {
if (myVec->sz >= myVec->capacity) {
int newCap = myVec->capacity * 2;
myVec->data = realloc(myVec->data, newCap * sizeof(int));
} else {
for (int i = 0; i < myVec->capacity; i++) {
*(myVec->data + i) = *(myVec->data + i + 1);
}
myVec->data = &newE;
}
myVec->sz++;
}
void intVecPop(IntVec myVec) {
for (int i = 0; i < myVec->capacity; i++) {
*(myVec->data - i) = *(myVec->data - i + 1);
}
myVec->sz--;
}
Run Code Online (Sandbox Code Playgroud)
这是测试文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "intVec.c"
int main() {
struct IntVec v;
v.intVecPush(v,0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
每次运行测试文件时,都会出现错误:
test.c:7:16: error: variable has incomplete type 'struct IntVec'
struct IntVec v;
^
test.c:7:9: note: forward declaration of 'struct IntVec'
struct IntVec v;
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
我尝试将测试文件中的#include "intVec.c"to更改为"intVec.h",但是会产生相同的错误。为了不出现此错误,我需要更改什么?
没有结构定义struct IntVec。
所以编译器无法定义该对象v
struct IntVec v;
Run Code Online (Sandbox Code Playgroud)
我想你的意思是
IntVec v;
Run Code Online (Sandbox Code Playgroud)
还有这个电话
v.intVecPush(v,0);
Run Code Online (Sandbox Code Playgroud)
是无效的,没有意义。我认为应该有类似的东西
IntVec v = intMakeEmptyVec();
intVecPush(v,0);
Run Code Online (Sandbox Code Playgroud)
代替
struct IntVec v;
v.intVecPush(v,0);
Run Code Online (Sandbox Code Playgroud)
将整个模块包含在另一个模块中也是一个坏主意。您应该将结构体定义放在标头中,并将该标头包含在 main 的编译单元中。
那就是移动这些定义
typedef struct IntVecNode {
int* data;
int sz; // Number of elements that contain data
int capacity; // How much is allocated to the array
} IntVecNode;
typedef struct IntVecNode* IntVec;
Run Code Online (Sandbox Code Playgroud)
在标题中。
| 归档时间: |
|
| 查看次数: |
24734 次 |
| 最近记录: |