簡體   English   中英

C語言無法執行二進制搜索功能並將數組傳遞給函數?

[英]C language i m having trouble doing Binary search function and passing array to function?

用於二進制搜索的C程序

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>   

typedef struct node {   //LINKED LIST FUNCTION
        char *words;
         struct node *next;
                } Node;

//從文件中讀取單個單詞還會分配所需的空間。

    char *strdup (const char *s) {
            char *d = malloc (strlen (s));
                if (d == NULL) return NULL;
                    strcpy (d,s);
                     return d;
           }
     int main (int argc, char *argv[])
    {
    FILE *file1;
    FILE *file2;
    FILE *file3;

    file1 = fopen (argv[1],"r");
    file2 = fopen (argv[2],"r");


    char letters [100];
    char tempLetters [100][50]; 

// I tempLetters FOR BINARY SEARCH,其中存儲了單詞

 Node *current , *head;
    int check;
    head = current = NULL;
    int i = 0;

 while (! feof (file1)){
            fscanf (file1,"%s",letters);
            Node * list = malloc (sizeof (Node));
            list -> words = strdup(letters);
            list -> next = NULL;
    if(head == NULL){
        current = head = list;
    } else {
        current = current->next = list;
    }
    // printf ("%s\n", current->words);
            strcpy (tempLetters[i],current -> words);

//在這里,我在臨時字母中存儲單詞

    i++; 

// i ++用於跟蹤多少個單詞。 }

    // FILE 2 reading queries:
    char query [100]; //Just a local variable 
    int q = 0;
    char QArray [100][50];//NEED THIS ONE FROM BINARY SEARCH
    while (!feof (file2)){
            fscanf (file2, "%s", query);
    if (!feof (file2)){

    //Keeping track of how many words
    strcpy  (QArray[q], query);
             q++;  
       }
        }

} / * //二進制搜索我想從QArray中讀取單個單詞,然后發現temLetters數組中是否存在相同的單詞。 如果有,則打印該單詞並打印其陣列索引。 如果沒有,則從QArray讀取下一個單詞,直到QArray == NULL。 我在功能上無法通過這些數組。 * /

    fclose (file1);
    fclose (file2);

    return 0;}

char *d = malloc (strlen (s)); 是錯的。 您需要char *d = malloc (strlen (s) + 1); 首先需要解決。 它可能會也可能不會解決其他錯誤。 – R Sahu

暫無
暫無

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

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