如何从main()外部的函数返回指针

时间:2018-12-01 14:20:52

标签: c pointers dynamic-memory-allocation

我的问题是有关C中的动态内存分配。有人要求我动态分配一个n long数组,然后将指针返回该数组的第一个元素。我有一些代码可以测试此输出,但是内存分配失败。

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

我在两行提示

时出错
  

“错误:返回使指针从整数开始而没有强制转换”

这是针对行

return 1;

return *a;

我不确定如何解决此问题。我认为return 1;中的错误是我在寻找指针时试图返回一个整数?但是我不确定如何修复它以返回指针。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

要修复原始版本,请执行以下操作:

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()
}

写这样的分配的更好的方式 tm

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

通过使用*foo*bar作为sizeof的操作数,您不必担心在foobar类型的情况下更改它变化。

您的功能可以简化为

#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.

*),以便用户立即获得消息。

而且,由于它们返回的*alloc()在其他所有指针类型中都可以隐式转换,因此也无需转换void*的结果。

可以写为宏,因此它不仅适用于long,而且适用于任何类型:

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