提供函数指针时,取消引用指向不完整类型的指针

时间:2017-08-28 17:12:28

标签: c struct function-pointers

当我尝试运行以下代码时,我正在获取指向不完整类型错误的解除引用指针。我已经检查过有关此错误的其他几个问题,而且我可以告诉它不是由于缺少或额外的struct关键字,我相信指针类型是正确的,但我可能会弄错。

代码可能存在其他问题,因为我只是在学习C,我很乐意尝试自己解决这个问题我似乎无法追踪问题。不完整类型错误。

SELECT * FROM tablename WHERE value = STUFF(95341,4,0,'-')

test.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) ) {

lrGraph.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();
}

lrGraph.h

#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;
}

1 个答案:

答案 0 :(得分:5)

“不完整类型”表示编译器看到您正在尝试使用结构类型,但该结构没有定义。

如果您只使用指向结构的指针(并且实际上是如何在C中实现抽象数据类型),这很好,但是如果您想取消引用这样的指针,则结构定义必须是可见的。

test.c中,只有lrGraph.h的内容可见(即typedef struct lrgraph_node lrgraph_node;),但实际的struct lrgraph_node { ... };定义仅存在于lrGraph.c

可能的解决方案:将struct lrgraph_node { ... }定义移到标题中。 (或者,将compare的定义放入lrGraph.c)。