簡體   English   中英

從C函數返回數組

[英]Returning an array from a C-function

我目前正在編寫一個需要C函數返回數組的應用程序。 我已經讀到C函數不能直接返回數組,而只能返回指向數組的指針,無論如何我還是無法使它起作用。 我正在發送一個帶有幾個數值的字符串,這些數值必須放入數組中。

我的代碼如下所示,主要功能是:

int main() {
    char arr[3] = {0};
    char *str = "yaw22test242test232";
    foo(arr,3,str);

    printf("%d\n",arr[0]);

    return 0;
}

我想讓foo函數返回分別在數組位置0、1和2上分別為22、242和232的數組。 foo函數中的算法在主程序中使用時可以正常工作,但不能以這種方式工作。 有什么辦法可以解決此問題? 我究竟做錯了什么? foo函數如下所示:

void foo(char *buf, int count, char *str) {
    char *p = str;
    int k = 0;

    while (*p) { // While there are more characters to process...
        if (isdigit(*p)) { // Upon finding a digit, ...
            double val = strtod(p, &p); // Read a number, ...
            //printf("%f\n", val); // and print it.
            buf[1-count-k] = val;
            k++;
        } else { // Otherwise, move on to the next character.
            p++;
        }
    }
}

好吧,您在這里越界越好:

buf[1-count-k] = val;

也許您的意思是buf[k] = val; 然后檢查if( k >= count )以結束循環。

由於char *buf通常不能表示大於127的值,因此應使用足夠大的整數類型或雙精度類型,否則賦值buf[*] = val; 從double類型到char類型,將導致未定義的行為。

看起來您想將字符串中的數字提取為double ,但是您正在嘗試將它們存儲在char數組中。 這甚至不編譯。

因此,首先,使用適當的緩沖區:

int main() {
    double arr[3] = {0};
    /* ... */
}

並更新foo()的參數聲明:

void foo(double *buf, int count,char *str) { ... }

然后解決此問題:

buf[1-count-k] = val;

您可能想要一些簡單的東西:

buf[k++] = val;

最后,您可能需要返回k以便調用者有機會知道向數組中寫入了多少個數字。 因此, foo將如下所示:

size_t foo(double *buf, int count,char *str) {
    char *p = str;
    size_t k = 0;

    while (*p) { // While there are more characters to process...
        if (isdigit(*p)) { // Upon finding a digit, ...
            double val = strtod(p, &p); // Read a number, ...
            //printf("%f\n", val); // and print it.
            buf[k++] = val;
        } else { // Otherwise, move on to the next character.
            p++;
        }
    }
    return k;
}

請注意,索引數組的正確類型是size_t ,而不是int size_t保證足夠寬,可以容納任何數組的大小,因此,如果您希望代碼使用任意長的數組,則應該使用size_t對數組進行索引。

我建議使用類似矢量的結構而不是數組。 已經有許多實現(請參閱C的GLib列表)。 但是,如果您想“自己動手”,請嘗試類似的操作:

typedef struct
{
    char** data;
    int size;

} str_vector;

您可以在其中動態分配str_vector及其data成員,然后返回它。 我將不做過多介紹,因為互聯網上有很多教程,我相信您可以在幾秒鍾內在Google / Bing / Whatever中找到它們:)

暫無
暫無

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

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