简体   繁体   English

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

[英]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. 我的问题是关于C中的动态内存分配。有人要求我动态分配n long数组,然后将指针返回该数组的第一个元素。 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; 我认为错误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. 通过使用*foo*bar作为sizeof的操作数,您不必担心在foobar的类型更改时更改它。

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. 另外,由于它们返回一个void* ,因此在每个其他指针类型中都可以隐式转换,因此无需转换*alloc()的结果。

Could be written as a macro so it not only works for long but for any type: 可以写为宏,因此它不仅可以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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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