我想創建一個初始大小爲len
的新的intarr_t
,但我從來沒有用typedef
'ed變量處理這類問題。在函數中對typedef創建的變量使用malloc
我的問題是intarr_create()
應該分配數組空間,然後返回一個指向它的指針,如果malloc成功或者指向NULL
,如果我失敗了。我怎樣才能解決這個問題?
此外,爲什麼函數中有一個*符號?
這裏是我的代碼:
#include <stdio.h>
typedef struct {
int* data;
unsigned int len;
} intarr_t;
intarr_t* intarr_create(unsigned int len) {
//intarr_t with initial size len
intarr_t = (int *) malloc(len); // not working here, can someone explain why?
if(intarr_t != NULL) {
return intarr_t;
} else {
return NULL;
}
}
int main() {
int len = 15;
int h = intarr_create(len);
printf("%d\n", h);
return 0;
}
注意,['typedef''ing結構](http://stackoverflow.com/a/4566358/1757964)是C語言的最壞,最可怕的弊端之一。如果你可以避免使用它,請這樣做。 – APerson 2014-11-05 19:27:33
您正嘗試在'main'的函數調用中將指針類型分配給非指針類型。你也可以直接返回'malloc'的結果,如果你打算在失敗時返回NULL,[並且不要強制轉換'malloc'的結果](http://stackoverflow.com/questions/605845/do -i-cast-of-malloc) – IllusiveBrian 2014-11-05 19:28:05
@APerson這有點極端,它有一些優點和很少的缺點 – 2014-11-05 19:51:15