我目前正在c中模拟adt,我本来应该创建一个二进制搜索树来调用字符串,我现在正在开始编码,但是我得到了这个错误并且没有说错误的来源,这是代码,有人可以帮助我。
//Tree.h
#ifndef tree_h
#define tree_h
#include <stdbool.h>
#include <stdlib.h>
typedef struct tree_node* node_ptr;
struct tree_node {
char* word;
node_ptr leftNode, rightNode;
};
node_ptr start = NULL;
void addItem(char*, int);
void display();
#endif
//tree.c
#include "tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void addItem(char arr[], int mode) {
node_ptr temp, temp2;
temp = (node_ptr)malloc(sizeof(struct tree_node));
temp->leftNode=NULL;
temp->rightNode=NULL;
if(mode == 1){
temp->word = arr;
start = temp;
}
}
void display() {
node_ptr temp;
temp = start;
printf("%s", start->word);
}
//main.c
#include "tree.h"
#include <stdio.h>
#include <conio.h>
int main() {
char word[31];
printf("Enter Root Word: ");
gets(word);
addItem(word, 1);
}
答案 0 :(得分:16)
问题在于tree.h
中的陈述。
node_ptr start = NULL;
您在tree.h
和main.c
中加入了tree.c
。这给出了全局范围内的变量start
的多重定义错误。你真正需要的是,
// tree.h
extern node_ptr start;
将定义放在单个源文件中,如 -
// tree.c
#include "tree.h"
........
node_ptr start = null;
答案 1 :(得分:7)
您所说的错误是:
... multiple definition of `start'
由于node_ptr start = NULL;
中有tree.h
,因此包含tree.h
的每个编译单元都有自己的变量start
定义。当需要链接时,链接器将看到变量start
的多个定义并抛出错误。
为避免这种情况,请在start
中定义 tree.c
:
node_ptr start;
然后将start
声明为extern
,以便其他编译单位了解它,但不会尝试在头文件tree.h
中自行定义:
extern node_ptr start;
答案 2 :(得分:3)
您的错误是您定义:
node_ptr start = NULL;
在您的头文件中,因此当您导入它时(无论宏保护程序如何),您将获得两次重新定义的开始。
答案 3 :(得分:1)
if(mode == 1)
{
temp->word = arr;/*here is another error*/
start = temp;
}
arr是main的本地,我认为对于更多的节点,你必须重用arr数组来获取input.at它反映在所有节点中,因为你的每个节点的单词指向相同的内存位置。所以它不是直接分配的选项。
你必须为字符串分配内存,然后使用strcpy()函数将数据复制到动态内存位置。
确定在那个地方使用此代码: -
if(mode==1)
{
w_len=sizeof(char)*(strlen(arr)+1);//one extra character for null character
temp->word=malloc(w_len);
strcpy(temp->word,arr);
start=temp;
}