簡體   English   中英

不明白tsearch返回指針是如何工作的

[英]Don't understand how tsearch return pointers work

我一直在試圖弄清楚tsearch庫是如何工作的,而且我已經達到了我完全被難倒的程度。 這是我的代碼:

#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <stdlib.h>
#include <dirent.h>
#include <utime.h>
#include <sys/wait.h>
#include <sys/msg.h>
#include <signal.h>
#include <ctype.h>
#include <search.h>

int compare (const void *a, const void *b);
void action(const void *nodep, VISIT value, int level);

struct word {
    char word[100];
    int occur;          
};

int main (void) {
    void *root = NULL;
    char *words[] = {"a","b","c","a"};
    struct word *entry = malloc(10 * sizeof(struct word));  
    struct word *ptr;
    struct word *ptr2;
    int i;  

    for (i=0;i<4;i++) {
        memcpy(entry[i].word,words[i],100);
        entry[i].occur = 1;                 
        ptr = tfind(&entry[i],&root,compare);
        if (ptr == NULL) {          
            tsearch(&entry[i],&root,compare);
        }
        else {              
            printf("%i\n",ptr->occur);
            printf("%i\n",entry[0].occur);          
            entry[0].occur++;           
        }
    }
    twalk (root, action);   
    //tdestroy (&rootp,freefct);
    return 0;
}

int compare (const void *a, const void *b) {
    const struct word *w1, *w2;

    w1 = (const struct word *) a;
    w2 = (const struct word *) b;

    return strcmp(w1->word, w2->word);
}

void action(const void *nodep, VISIT value, int level) {
    struct word *w = *((struct word **) nodep);
    switch (value) {
    case leaf:
    case postorder:
        printf("%s: %i\n",w->word, w->occur);
        break;
    default:
        break;
    }
    return;
}

現在,我認為ptr應該指向entry [0](因為這是它找到的值的地方)和ptr->出現應該給出“a”的出現值。 但事實並非如此。 它給了我0,如下面的結果所示:

0 1 a:2 b:1 c:1

更改條目[0]的值會改變在步行期間打印的內容。

我已經嘗試了解除引用或構建ptr的每一種組合,我可以想到,將其聲明為void *或結構字* ...

所以我的問題主要是:

給定從tfind返回(以及應該聲明的內容),如何訪問struct中的值?

來自tfind的返回值不是條目,它是指向樹內部節點結構的指針,其第一個元素是指向條目的指針。 由於節點結構是不透明的,您可以將ptr視為結構字**。

如果你重寫你的其他部分

    else {
        printf("i=%d ptr=%p *ptr=%p entry=%p,%p,%p,%p\n", i, ptr, *(struct word **)ptr, entry, entry+1, entry+2, entry+3);
        printf("wrong: %i\n",ptr->occur);
        printf("right: %i\n",(*(struct word **)ptr)->occur);
        printf("right: %i\n",entry[0].occur);
        entry[0].occur++;
    }

你會得到的(至少在我的機器上)

i=3 ptr=0x8f32430 *ptr=0x8f32010 entry=0x8f32010,0x8f32078,0x8f320e0,0x8f32148
wrong: 0
right: 1
right: 1
a: 2
b: 1
c: 1

如你所見,它不是指向elem [0]的ptr,而是* ptr。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM