幾個問題。
首先,你在所有地方都有不兼容的類型。在線路
my_struct = some_func(my_struct);
my_struct
具有類型struct stu1 **
,但some_func
定義預計類型的參數;這兩種類型是不一樣的。指向T的指針與指向T的指針的類型不同。
其次,您的體操操作不會像您期望的那樣工作。指針類型不會自動兼容;它們的基本類型必須兼容,並且不同的結構類型是不兼容的,即使他們的佈局是相同的,例如:
struct {int x, int y} foo;
struct {int x, int y} bar;
struct S {int x, int y} blurga;
struct S bletch;
foo
,bar
和bletch
是不同類型的,但並不兼容,即使他們的佈局是一樣的。 blurga
和bletch
是相同類型的(結構S)。如果struct stu2
或struct stu3
與struct stu1
有不同的大小,則不會爲my_struct2
和my_struct3
分配適當的內存量。
爲了清楚起見和你的理智,你應該有不同的分配功能,對每種類型,而不是試圖迫使方釘成五角形孔:
struct stu1 **stu1_alloc(size_t count)
{
struct stu1 **arr = malloc(sizeof *arr * count);
if (arr)
{
size_t i;
for (i = 0; i < count; i++)
{
arr[i] = malloc(sizeof *arr[i]);
if (arr[i])
{
// initialize arr[i] as necessary
}
}
}
return arr;
}
struct stu2 **stu2_alloc(size_t count)
{
struct stu2 **arr = malloc(sizeof *arr * count);
if (arr)
{
size_t i;
for (i = 0; i < count; i++)
{
arr[i] = malloc(sizeof *arr[i]);
if (arr[i])
{
// initialize arr[i] as necessary
}
}
}
return arr;
}
struct stu3 **stu3_alloc(size_t count)
{
struct stu3 **arr = malloc(sizeof *arr * count);
if (arr)
{
size_t i;
for (i = 0; i < count; i++)
{
arr[i] = malloc(sizeof *arr[i]);
if (arr[i])
{
// initialize arr[i] as necessary
}
}
}
return arr;
}
int main(void)
{
struct stu1 **my_struct = stu1_alloc(SIZE);
struct stu2 **my_struct2 = stu2_alloc(SIZE2);
struct stu3 **my_struct3 = stu3_alloc(SIZE3);
...
}
是,之間唯一不同的三種分配函數是類型。但是,如果不同的結構類型具有不同的大小或不同的初始化需求,那麼這是必需的。
注意幾件事情。首先,我不是在輸入malloc()
的結果。有兩個原因。一,從C89及以後,你不必:malloc()
返回一種void *
,它隱式轉換爲目標指針類型。兩個,更重要的是,如果我忘記包含stdlib.h,或者沒有原型在malloc()
範圍內,則關閉該類型將觸發「不兼容類型」警告(因爲未聲明的函數被假定爲返回int
,並且你不能將一個int值隱式轉換爲一個指針類型)。如果您施放了malloc()
的返回值,那麼您在運行時禁止該警告並存在風險問題(因爲由malloc()
返回的值將從void *
轉換爲int
,然後從int
轉換爲目標指針類型,但不保證可以正常工作)。
其次,我在對象上使用的是sizeof
,而不是類型。這有兩個好處。一,代碼有點容易閱讀。二,如果我改變對象的類型,我不必回去改變對malloc()
的每個調用。
如果你真的不想有三個獨立的分配功能,你可以嘗試一些宏觀魔術這樣的:
#define ALLOC_STU(target, size) \
do { \
target = malloc(sizeof *target * size); \
if (target) \
{ \
size_t i; \
for (i = 0; i < size; i++) \
{ \
target[i] = malloc(sizeof *target[i]); \
} \
} \
} while(0)
int main(void)
{
struct stu1 **my_struct;
...
ALLOC_STU(my_struct, SIZE);
...
}
雖然我覺得單獨分配功能的更安全的方法走。
您錯過了'some_func'中的return語句,並且您可能在參數和返回語句中輸入了錯誤的*號。請注意告訴我們代碼的用意是什麼? – 2010-03-23 14:39:20
我們的目的是需要以相同的方式填充不同的結構(相同的佈局)some_func() – clear2k 2010-03-23 14:50:54
這裏存在一個真正的問題,因爲您顯然想要做一些複雜的事情,比如將指針數組分配給結構,或者一些東西,但是因爲你已經中止了所有的變量名,並且沒有說明代碼試圖完成什麼,所以任何人都很難提供幫助。 – 2010-03-23 14:52:24