【发布时间】:2017-09-14 23:09:44
【问题描述】:
我正在为我的数据结构课程做作业,但我对 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
这是我所做的 .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--;
}
这是测试文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "intVec.c"
int main() {
struct IntVec v;
v.intVecPush(v,0);
return 0;
}
每次运行测试文件时,我都会收到错误:
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.
我已尝试将测试文件中的 #include "intVec.c" 更改为 "intVec.h",但这会产生相同的错误。为了不出现此错误,我需要进行哪些更改?
【问题讨论】:
-
使用实际存在的类型。您的代码中没有
struct IntVec。 -
另外,您应该包含
.h文件而不是.c文件。包含.c文件是正确的做法是极其罕见的。 -
将 main 更改为
IntVec v = intMakeEmptyVec(); intVecPush(v, 0);。尽管我建议不要使用指针 typedef,因为它们会造成混淆(看起来您的代码正在按值复制 intvec,但实际上并非如此) -
使用这个库的代码会泄露! (没有办法释放 vec)
标签: c struct compiler-errors incomplete-type