[英]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.