Lia*_*yan 1 c struct function-pointers
当我尝试运行以下代码时,我正在获取指向不完整类型错误的解除引用指针.我已经检查了几个关于这个错误的其他问题,从我可以告诉它不是由于缺少或额外的struct关键字,我相信指针类型是正确的但我可能会弄错.
代码可能还有其他问题因为我只是在学习C,我很乐意尝试自己解决这个问题我似乎无法用不完整的类型错误来追踪问题.
Development/C/AI/test/src/test.c: In function ‘compare’:
Development/C/AI/test/src/test.c:10:19: error: dereferencing pointer to incomplete type ‘lrgraph_node {aka struct lrgraph_node}’
if ( strcmp(other->dataType, current->dataType == 0) ) {
Run Code Online (Sandbox Code Playgroud)
test.c的
#include "lrGraph.h"
#include <string.h>
int data = 1;
char *dataType = "int";
lrgraph_edge *connected[] = {};
unsigned numEdges = 0;
int compare( lrgraph_node *other, lrgraph_node *current ) {
if ( strcmp(other->dataType, current->dataType == 0) ) {
return (int)other->data - (int)current->data;
}
return -1;
}
int main() {
lrgraph_node *nodeA = lrgraph_createNode((void*)&data, dataType, &compare, connected, numEdges);
lrgraph_printVersion();
}
Run Code Online (Sandbox Code Playgroud)
lrGraph.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lrGraph.h"
struct lrgraph_edge {
float weight;
lrgraph_node *nodeA;
lrgraph_node *nodeB;
};
struct lrgraph_node {
//data can be of any type
void *data;
//string to see if this node can be compared to another node based on data type
char *dataType;
int numEdges;
//comparator function which compares another node to this node
int (*compare)(lrgraph_node *other, lrgraph_node *current);
//array of connected edges
lrgraph_edge *connected[];
};
void lrgraph_printVersion() {
fprintf(stdout, "\nlrgraph version 0.01b\n");
}
lrgraph_node* lrgraph_createNode(void *data, char *dataType, int (*compare)(lrgraph_node* other, lrgraph_node* current), lrgraph_edge *connected[], unsigned numEdges) {
//allocate enough memory for the struct plus each pointer in the array of edges - https://stackoverflow.com/questions/32311269/can-we-have-a-struct-element-of-type-variable-length-array
lrgraph_node *node = malloc(sizeof(lrgraph_node) + numEdges * sizeof(lrgraph_edge));
if (NULL != node) {
node->data = data;
node->dataType = strdup(dataType);
node->compare = compare;
node->numEdges = numEdges;
//initialize each edge in the array
for( unsigned i=0; i < numEdges; i++) {
node->connected[i] = connected[i];
}
}
return node;
}
Run Code Online (Sandbox Code Playgroud)
lrGraph.h
#ifndef LRGRAPH_H
#define LRGRAPH_H
typedef struct lrgraph_node lrgraph_node;
typedef struct lrgraph_edge lrgraph_edge;
lrgraph_node* lrgraph_createNode(void *data, char *dataType, int (*compare)(lrgraph_node *other, lrgraph_node *current), lrgraph_edge *connected[], unsigned numEdges);
void lrgraph_printVersion();
#endif /*LRGRAPH_H*/
Run Code Online (Sandbox Code Playgroud)
"不完整类型"表示编译器发现您正在尝试使用结构类型,但该结构没有定义.
如果你只使用指向结构的指针(实际上是如何在C中实现抽象数据类型),这很好,但如果你想取消引用这样的指针,结构定义必须是可见的.
在test.c唯一的内容lrGraph.h是可见的(即typedef struct lrgraph_node lrgraph_node;),但实际struct lrgraph_node { ... };的定义只存在于lrGraph.c.
可能的解决方案:将struct lrgraph_node { ... }定义移动到标题中.(或者,将定义compare放入lrGraph.c).