简体   繁体   中英

Return array from a function using a pointer C

I am trying to understand pointers and functions, specifically how to use a pointer when returning an array from a function. I tried to write some code to see if I understand it but I clearly don't. Could you please look over and tell me what I am doing wrong? Thank you.

#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);
}

Your code has many problems, the most important one is that you did not allocate space for c .

Don't use static if you don't really know why it is useful, it's certainly not useful in this situation.

The other important issue is the declaration of x and y , they should be declared as arrays, ie

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} ;

You could do it like this

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;
}

And then your main() could look like this

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM