我试图理解C中的指针,链表,结构等。作为一种学习经历,我写了这个小程序,其中:
insertEntry
,它在链接列表的一个元素和他的直接关注者之间插入一个给定的结构。This Stack Overflow answer说:"这实际上意味着源代码结构中的其他地方还有另一个函数/声明[..],它具有不同的函数签名。"
insertEntry
的两个参数总是两个相同类型的结构。 This different Stack Overflow answer说:"您已忘记#include "client.h"
,所以定义",但我也检查过。文件系统上的实际文件名和#include
。
===>我不知道,我的错误在哪里。
ex1_insertStructure_linkedList.h:
void insertEntry(struct entry, struct entry);
ex1_insertStructure_linkedList.c:
#include <stdio.h>
#include "ex1_insertStructure_linkedList.h"
struct entry {
int value;
struct entry *next;
};
// clangtidy: conflicting types for 'insertEntry' [clang-diagnostic-error]
void insertEntry(struct entry given_entry, struct entry entry_to_insert) {
printf("Print inside insertEntry method: %i\n", given_entry.value);
struct entry *second_pointer = (given_entry).next;
// entry_to_insert is now the element in the middle
given_entry.next = &entry_to_insert;
// the third element
entry_to_insert.next = second_pointer;
return;
}
int main(int argc, char *argv[]) {
struct entry n1, n2, n3;
n1.value = 1;
n1.next = &n2;
n2.value = 32;
n2.next = &n3;
n3.value = 34242;
n3.next = (struct entry *)0;
struct entry *list_pointer = &n1;
while (list_pointer != (struct entry *)0) {
int printValue = (*list_pointer).value;
list_pointer = (*list_pointer).next;
printf("%i\n", printValue);
}
printf("--------------------\n");
list_pointer = &n1;
struct entry a;
a.value = 999999;
a.next = (struct entry *)0;
// clangtidy: argument type 'struct entry' is incomplete [clang-diagnostic-error]
insertEntry(n1, a);
while (list_pointer != (struct entry *)0) {
int printValue = list_pointer->value;
list_pointer = list_pointer->next;
printf("%i\n", printValue);
}
return 0;
}
答案 0 :(得分:3)
您应该在{strong> ex1_insertStructure_linkedList.h 中放置struct entry
声明:
struct entry {
int value;
struct entry *next;
};
void insertEntry(struct entry, struct entry);
答案 1 :(得分:2)
您需要在文件entry
中“转发声明”结构ex1_insertStructure_linkedList.h
,即在函数声明之前:void insertEntry(struct entry, struct entry);
,之前放置以下struct entry;
那个功能宣言。
这是因为当编译器遇到insertEntry(struct entry, struct entry);
时,它对struct entry
一无所知。通过正向声明struct entry
,您可以“确保”编译器在源文件中的某处定义了struct entry
。