简体   繁体   中英

How do you return a pointer from a function outside of main()

My question is aboutt dynamic memory allocation in C. I have been asked to dynamically allocate an array of n longs, and return the pointer to the first element of this array. I have some code to test the output of this but the memory allocation is failing.

long* make_long_array(long n)
{
    int i;
    int *a;

    a = (int*)malloc(sizeof(int)*n);
    if (a == NULL) {
        printf("ERROR: Out of memory\n");
        return 1;
    }

    for (i = 0; i < n; *(a + i++) = 0);
    return *a;
}

Im getting an error on two lines saying

'error: return makes pointer from integer without cast'

this occurs for the lines

return 1;

and

return *a;

I'm not entirely sure how to fix this. I think the error in return 1; being that I am trying to return an integer when it is looking for a pointer? But I am not sure how to fix it for the return of the pointer. Any help would be much appreciated.

To fix your original version:

long* make_long_array(/* long not the correct type for sizes of objects */ size_t n)
{
    // int i;  define variables where they're used.
    /* int you want to return a */ long *a; // array.

    a = /* (int*) no need to cast */ malloc(sizeof(/* int */ you want */ long /*s, remember? *) */ ) * n);
    if (a == NULL) {
        printf("ERROR: Out of memory\n");  // puts()/fputs() would be sufficient.
        return /* 1 */ NULL;  // 1 is an integer. Also it is uncommon to return
    }                         // anything other than NULL when a memory allocation
                              // fails.

    for (size_t i = 0; i < n; /* *(a + i++) = 0 that falls into the category obfuscation */ ++i )
        /* more readable: */ a[i] = 0;
    // return *a; you don't want to return the first long in the memory allocated
    return a; // but the address you got from malloc()
}

A Better Way tm to write such allocations is

FOO_TYPE *foo = malloc(NUM_ELEMENTS * sizeof(*foo)); // or
BAR_TYPE *bar = calloc(NUM_ELEMENTS, sizeof(*bar));

By using *foo and *bar as the operand of sizeof you don't have to worry about changing it when the type of foo or bar changes.

Your function can be simplified to

#include <stddef.h>  // size_t
#include <stdlib.h>  // calloc()

long* make_long_array(size_t size)      // size_t is guaranteed to be big enough to hold
{                                       // all sizes of objects in memory and indexes
    return calloc(size, sizeof(long));  // into them. calloc() initializes the memory
}                                       // it allocates with zero.

// if you really want an error-message printed:

long* make_long_array(size_t size)
{
    long *data = calloc(size, sizeof(long));
    if (!data)  // calloc() returned NULL
        fputs("Out of memory :(\n\n", stderr);  // Error messages should go to stderr
    return data;                                // since it is unbuffered*) and
}                                               // might be redirected by the user.

*) so the user gets the message instantly.

Also there is no need to cast the result of *alloc() since they return a void* which is implicitly convertible in every other pointer type.

Could be written as a macro so it not only works for long but for any type:

#include <stddef.h>
#include <stdlib.h>

#define MAKE_ARRAY(TYPE, COUNT) calloc((COUNT), sizeof((TYPE)))

// sample usage:

int main(void)
{
    int  *foo = MAKE_ARRAY(*foo, 12);
    long *bar = MAKE_ARRAY(*bar, 24);
    char *qux = MAKE_ARRAY(*qux, 8);

    free(qux);
    free(bar);
    free(foo);
}

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