Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 无法使用指向结构的指针更改结构字段_C - Fatal编程技术网

C 无法使用指向结构的指针更改结构字段

C 无法使用指向结构的指针更改结构字段,c,C,我正在尝试更改此结构的“lineNumber”字段: typedef struct occurrenceType Occurrence; struct occurrenceType { char* line; int lineNumber; int wordNumber; Occurrence *next; }; 使用这段代码 Occurrence *occur; occur=(Occurrence*)malloc(sizeof(Occurrence)); (

我正在尝试更改此结构的“lineNumber”字段:

typedef struct occurrenceType Occurrence;

struct occurrenceType {
    char* line;
    int lineNumber;
    int wordNumber;
    Occurrence *next;
};
使用这段代码

Occurrence *occur;
occur=(Occurrence*)malloc(sizeof(Occurrence));
(*occur).lineNumber=34;
但当我打印(*出现)时,行号为零。我尝试了几种不同的结构和发生指针配置,但似乎没有任何效果。有人能看出我做错了什么吗?谢谢

编辑: 完整调用如下所示:

inFile=fopen(argv[1],"r");
while(fgets(line,100,inFile)!=NULL) {
    if(strstr(line,argv[2])!='\0') {
            (*occur).line=line;
            (*occur).lineNumber=34;
            (*occur).next=(Occurrence*)malloc(sizeof(Occurrence));
            occur=(*occur).next;
            printf("%d",(*occur).lineNumber);
    }
    count++;
}

它逐行读取文件并搜索命令行中提供的键,然后在每次出现时向链表中添加一个结构。

您正在打印新malloc'结构的字段。尝试反转最后两行:

    occur=(*occur).next;
    printf("%d",(*occur).lineNumber);
致:

根据您给我们的代码片段的上下文,还有一些其他注释:您应该将该结构设置为零,因为
malloc
不会为您这样做。它将包含垃圾,我假设您在沿着链接列表走的过程中,正在检查字段
next
中的
NULL
。将调用更改为
calloc()
可以解决此问题


其次,为什么要将行指针指定给字段
line
?这对于每个结构都是一样的,它的内容将是最后从文件中读取的内容。我想你是想保存离线阅读。尝试将它设为另一个缓冲区(或<代码> CALROUNE())/代码>它,以及<代码> STRCYPY()/>代码>找到它的数据。< /P>这是C代码,不是C++。在C++中,需要绘制<代码> MalOC 的结果。在C语言中这是一个坏主意,因为在C语言中,这只是告诉编译器不要包含必要的头。还要注意的是,不要使用
(*occure).lineNumber
,只需编写
occure->lineNumber
;-)看到这样的东西,我的第一反应是认为OP是在开玩笑,但我记得很多人都在写代码,就像写一系列咒语一样,根本不理解它的意思。
    printf("%d",(*occur).lineNumber);
    occur=(*occur).next;