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

tri*_*o32 2 c pointers dynamic-memory-allocation

我的问题是关于 C 中的动态内存分配。我被要求动态分配一个nlong数组,并返回指向该数组第一个元素的指针。我有一些代码来测试这个输出,但内存分配失败。

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;
}
Run Code Online (Sandbox Code Playgroud)

我在两行上收到一个错误说

'错误:返回使指针来自整数而不进行强制转换'

这发生在线路上

return 1;
Run Code Online (Sandbox Code Playgroud)

return *a;
Run Code Online (Sandbox Code Playgroud)

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

Swo*_*ish 5

要修复您的原始版本:

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()
}
Run Code Online (Sandbox Code Playgroud)

一个更好的方式以旧换新写这样的分配是

FOO_TYPE *foo = malloc(NUM_ELEMENTS * sizeof(*foo)); // or
BAR_TYPE *bar = calloc(NUM_ELEMENTS, sizeof(*bar));
Run Code Online (Sandbox Code Playgroud)

通过使用*fooand*bar作为操作数,sizeof您不必担心在fooor的类型发生变化时更改它bar

您的功能可以简化为

#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.
Run Code Online (Sandbox Code Playgroud)

*) 以便用户立即收到消息。

也没有必要对结果进行转换,*alloc()因为它们返回 a 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);
}
Run Code Online (Sandbox Code Playgroud)