简体   繁体   中英

Returning an integer array from a function in C

My program is as follows

#include<stdio.h>

int *intial(int);

int main (void)
{
    int i, *b;

    b=intial(5);
    for(i=0;i<5;i++)
        printf("%d\t",*(b+i));
    getch();
}

int *intial(int t)
{
    int i, *a; 

    for(i=0;i<t;i++)
        a[i]=i;
    return a;
}

But i am getting garbage values.

I also tried this

int *intial(int t)
{
    int i, a[10];

    for(i=0;i<t;i++)
        a[i]=i;    
    return a;
}

But it is not working.

In order to work properly, your function should read

int *intial(int t)
{
    int i;
    int *a = malloc(t * sizeof(*a));
    if (!a) return NULL; // error checking
    for(i=0;i<t;i++) {
        a[i]=i;
    }
    return a;
}

The "calling treaty" for this function is that the pointer returned is a malloc() ed one which the caller has the obligion for to free() it.

Of course, the caller as well should do proper error checking:

int main()
{
    int i;
    int *b;
    b=intial(5);
    if (!b) {
        fprintf(stderr, "Malloc error.\n");
        return 1;
    }
    for(i=0;i<5;i++) {
        printf("%d\t",*(b+i)); // *(b+i) should be replaced with b[i] for readability
    }
    free(b); // free the memory
    return 0;
}

You need to allocate memory for your array with malloc() . Otherwise a , and hence b , will not point to anything in particular.

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