簡體   English   中英

使用指針C從函數返回數組

[英]Return array from a function using a pointer C

我試圖理解指針和函數,特別是從函數返回數組時如何使用指針。 我試圖編寫一些代碼以查看是否理解,但我顯然不明白。 您能看看我告訴我我做錯了嗎? 謝謝。

#include <stdio.h>

int *elmntsum(int *a, int *b);

int main()
{
    int *z;
    int x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int y = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} ;

    z = elmntsum(x, y);

    int t;

    for (t = 0 ; t < 10 ;t++){
        printf( "%d\n", z[t]);
    }
    return(0);
}

int *elmntsum(int *a, int *b){
    static int *c;
    int t;

    for (t = 0 ; t < 10 ;t++){
        c[t] = a[t] + b[t];
    }
    return(c);
}

您的代碼有很多問題,最重要的是您沒有為c分配空間。

如果您真的不知道它為什么有用,請不要使用static ,在這種情況下它肯定是沒有用的。

另一個重要的問題是xy的聲明,它們應聲明為數組,即

int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int y[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} ;

你可以這樣

int *elmntsum(int *a, int *b, size_t count) {
    int *c;

    c = malloc(count * sizeof(*c));
    if (c == NULL)
        return NULL;
    for (size_t t = 0 ; t < count ;t++)
        c[t] = a[t] + b[t];
    return c;
}

然后您的main()可能看起來像這樣

int main()
{
    int *z;
    int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int y[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} ;

    z = elmntsum(x, y, 10);
    if (z == NULL)
        return -1;
    for (size_t t = 0 ; t < 10 ;t++){
        printf("%d\n", z[t]);
    }
    free(z);
    return 0;
}

暫無
暫無

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

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