[英]How do you return a pointer from a function outside of main()
我的问题是关于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;
是我试图寻找指针时返回一个整数? 但是我不确定如何修复它以返回指针。 任何帮助将非常感激。
要修复原始版本:
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()
}
更好的方式 以旧换新写这样的分配是
FOO_TYPE *foo = malloc(NUM_ELEMENTS * sizeof(*foo)); // or
BAR_TYPE *bar = calloc(NUM_ELEMENTS, sizeof(*bar));
通过使用*foo
和*bar
作为sizeof
的操作数,您不必担心在foo
或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.
*),以便用户立即获得消息。
另外,由于它们返回一个void*
,因此在每个其他指针类型中都可以隐式转换,因此无需转换*alloc()
的结果。
可以写为宏,因此它不仅可以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.