繁体   English   中英

C错误中的PrintflinkedList

[英]Printf linkedList in C Errors

我正在尝试从文件读取数据。 文件的每一行包括:string1 string2 float在示例中:A1 A2 5.22我试图将链接列表的第一个元素的值打印到屏幕上,但是每次出现错误时:

在“ program.c”文件中-错误:请求成员“重量”的非结构体或联合体

printf("%f", data -> weight);

或在“ main.c”文件中-错误:取消引用不兼容类型的指针

printf("%f\n", data ->weight);

也许有人可以帮我将会员数据输出到屏幕上。 问题可能在哪里,我该如何解决? 因为我尝试阅读有关此主题的其他答案,所以尝试了不同的变体,但是“数据”成员没有任何结果。

编辑 :我已通过更改解决的问题:typedef struct node * node;
键入def struct node node;

但是出现“ main.c”错误:错误:取消引用不兼容类型的指针仍然存在。 也许有人有什么想法我该如何更正我的代码?

编辑代码:

main.c中

#include <stdio.h>
#include <stdlib.h>
#include "program.h"

int main(int argc, char *argv[] ){
    if(argc != 3){return 0;}
    node* data;
    data = getData(argv ,&data);
    printf("%f \n", data -> weight); //here second mentioned error appears

return 0;
}

program.h

#ifndef program_h
#define program_h

#include <stdio.h>
#include <stdlib.h>

#include "program.h"

typedef struct node node;  

node* getData (char* argv[], node** data);

#endif

program.c

#include "program.h"

struct node                                          
{   
    char* from;
    char* to;
    float weight;
    struct node *next;
};

node* getData (char* argv[], node** data){

    node* elem; 
    node* lastElem;

    FILE *in=fopen(argv[1], "r");
    if (in == NULL) {
        fprintf(stderr, "Can't open input file !\n");
        exit(1);
    } 

    char* string1 = (char*)malloc(100*sizeof(char));
    char* string2 = (char*)malloc(100*sizeof(char));;
    float dataW; // dataWeigth

    fscanf(in, "%s" ,string1);
    fscanf(in, "%s" ,string2);
    lastElem = malloc( sizeof(struct node));
    lastElem -> next = NULL;
    lastElem -> from = string1;
    *data = lastElem;
    printf("%f",(*data)->weight); 


    if(!feof(in)){
        fscanf(in, "%f%*[^\n]" ,&dataW);
        lastElem -> to = string2;
        lastElem -> weight = dataW;
        while (!feof(in)) 
         {
            fscanf(in, "%s" ,string1);
            fscanf(in, "%s" ,string2);
            fscanf(in, "%f%*[^\n]" ,&dataW);
            elem = malloc( sizeof(struct node));
            elem -> next = NULL;
            elem -> from = string1;
            elem -> to = string2;
            elem -> weight = dataW;
            lastElem -> next = elem;
            lastElem = elem;
         }
    }
    fclose(in);
 return *data; 

}

恩..我看不到program.c在main.c或program.h中的任何地方链接了

因为它应该在那里执行结构。 在没有将“数据”定义为结构的地方。 因为它应该是

struct node* data;

要么

node* data;

调用函数中的任何内容都不能使该结构成为结构。

更改

struct node                                          
{   
    char* from;
    char* to;
    float weight;
    struct node *next;
};

typedef struct                                          
{   
    char* from;
    char* to;
    float weight;
    struct node *next;
} node;

将其移动到program.h ,并且本身不包含program.h ,这没有任何意义。 而是将其同时包含在main.cprogram.c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM