4

現在、C で adt のシミュレーションを行っています。文字列を含むバイナリ検索ツリーを作成することになっています。現在コーディングを開始していますが、このエラーが発生し、エラーの原因がわかりません。コードは次のとおりです。 、誰かが私を助けることができます。

ツリー.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

ツリー.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);
}
4

4 に答える 4

18

問題は のステートメントにありtree.hます。

node_ptr start = NULL;

そして、 とtree.hの両方main.cに含めていますtree.cstartこれにより、グローバル スコープにある変数の複数定義エラーが発生します。実際に必要なのは、

// tree.h

extern node_ptr start;  

そして、次のような単一のソースファイルに定義があります-

// tree.c

#include "tree.h"
........
node_ptr start = null;
于 2012-07-24T00:03:12.383 に答える
7

あなたが話しているエラーは次のとおりです。

... multiple definition of `start'

を持っているので、インクルードnode_ptr start = NULL;するtree.h各コンパイル単位にtree.hは、変数の独自の定義がありますstart。リンクの段階になると、リンカーは変数の複数の定義startを確認し、エラーをスローします。

これを回避するには、 in を次のように定義 starttree.cます。

node_ptr start;

そして、 as を宣言startしてextern、他のコンパイル単位がそれを認識できるようにしますが、ヘッダー ファイルでそれ自体を定義しようとはしませんtree.h

extern node_ptr start;
于 2012-07-24T00:06:01.643 に答える
3

あなたのエラーは、あなたが定義することです:

node_ptr start = NULL;

ヘッダー ファイルでは、(マクロ ガードに関係なく) インポートすると、start の 2 つの再定義が行われます。

于 2012-07-24T00:03:26.003 に答える
1
if(mode == 1)
{
temp->word = arr;/*here is another error*/
    start = temp;
    }

arrはmainに対してローカルであり、より多くのノードについては、入力を取得するためにarr配列を再利用する必要があると思います。その時点で、各ノードの単語が同じメモリ位置を指しているため、すべてのノードに反映されます。したがって、直接行うオプションはありません。割当。

文字列にも動的にメモリを割り当てる必要があります。次に、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;
 }
于 2012-07-26T20:30:35.973 に答える