簡體   English   中英

C 中的小泛型編程問題

[英]Small generic programming issue in C

因此,我開始了解 C 中泛型編程的基礎知識。我目前正在構建一個程序,該程序可以說明某個值是否出現在給定的數字序列中。 我認為該錯誤發生在 cmpValues 函數中。 有人會指出嗎? (例如,對於want=4和v={1,2,3,4,5},程序說want不在v中)

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

void *search(const void *x, const void *t, int n, int d, int (*cmpValues)(const void *, const void *)){
    char *p = (char *)t;
    int i;
    for(i=0;i<n;++i)
        if(cmpValues(x,p+i*d))
            return p+i*d;
    return NULL;
}

int cmpValues(const void *a, const void *b){
    if((char *)a == (char *)b)
        return 1;
    return 0;
}

int main() {
    FILE *f = fopen("datein.txt", "r");
    FILE *g = fopen("dateout.txt", "w");
    int *v, n, i, want;
    fscanf(f, "%d", &n);
    v = (int *)malloc(n * sizeof(int));
    for(i = 0; i < n; ++i)
        fscanf(f, "%d", v + i);
    fscanf(f, "%d", &want);
    if(search(&want, v, n, sizeof(int), cmpValues))
        fprintf(g, "The value %d is found at position %d.\n\n", want, search(&want, v, n, sizeof(int), cmpValues));
    else
        fprintf(g, "The value does bot occur in the given sequence.\n\n");
    return 0;
}

在 cmpValues 中,您正在比較由 2 個空指針指向的 2 個對象(即您不知道它們的類型,也不知道它們的大小)。 讓我們假設我們有整數,並且整數有 4 個字節,通常是這種情況。

只是為了它,讓我們假設 a 指針的值為 0x100(即指向從 0x100 到 0x103 的 int,包括)和 b 指針的值為 0x104(即指向從 0x104 到 0x107 的 int)。

現在,您將它們轉換為 char*(char 有 1 個字節)並比較指針的值。 現在,指針的類型在比較中無關緊要。 在該比較中,您將比較內存地址(在我的示例中,0x100 和 0x104)。 顯然,函數返回 1 的唯一方式是指針指向同一個變量。

現在,為了修復它,您應該比較指針指向的內存地址處的值。 但是,只需取消引用指針:

*((char *)a) == *((char *)b)

這還不夠,因為這只會將 a 的第一個字節與 b 的第一個字節進行比較(假設 char 有 1 個字節)。 此外,您不能取消引用 void*。

因此,您需要遍歷變量並逐字節比較它們(假設您知道數據類型的大小):

int comp(void *a, void *b, int size) {
    // convert a and b to char* (1 byte data type)
    char *ca = a;
    char *cb = b;
    // iterate over size bytes and try to find a difference
    for (int i = 0; i < size; i++) {
        if (*(ca + i) != *(cb + j)) {
            return 0;
        }
    }
    // if no difference has been found, the elements are equal
    return 1;
}

旁注:您不需要在 main 中兩次調用cauta

暫無
暫無

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

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