gpt4 book ai didi

c - 为什么我一直得到 "error: variable has incomplete type ' struct intVec'?

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:47 25 4
gpt4 key购买 nike

我正在为我的数据结构类做作业,但我对 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

因此编译器无法定义对象v

struct IntVec v;

我想你的意思是

IntVec v;

还有这个电话

v.intVecPush(v,0);

无效且没有意义。我认为应该有类似的东西

IntVec v = intMakeEmptyVec();
intVecPush(v,0);

代替

struct IntVec v;
v.intVecPush(v,0);

将整个模块包含在另一个模块中也是一个坏主意。您应该将结构定义放在 header 中,并将此 header 包含在带有 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;

在标题中。

关于c - 为什么我一直得到 "error: variable has incomplete type ' struct intVec'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483564/

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