Altought,以前有這個問題的好答案,我無法避免添加我自己的。由於我在Collegue了PASCAL編程,我習慣了這樣做,在C相關的編程語言:
void* AnyFunction(int AnyParameter)
{
void* Result = NULL;
DoSomethingWith(Result);
return Result;
}
這幫助我輕鬆調試,避免像一個提到的@ysap錯誤,相關指針。
重要的是要記住的問題是,該問題提到返回一個單一的指針,這是一個常見的警告,因爲一個指針,可以用來解決單個項目,或連續的數組!
這個問題建議使用一個數組作爲CONCEPT,帶指針,不使用陣列語法。
// returns a single pointer to an array:
student_record* answer4(student_record* student, unsigned int n)
{
// empty result variable for this function:
student_record* Result = NULL;
// the result will allocate a conceptual array, even if it is a single pointer:
student_record* Result = malloc(sizeof(student_record)*n);
// a copy of the destination result, will move for each item
student_record* dest = Result;
int i;
for(i = 0; i < n ; i++){
// copy contents, not address:
*dest = *student;
// move to next item of "Result"
dest++;
}
// the data referenced by "Result", was changed using "dest"
return Result;
} // student_record* answer4(...)
檢查,這裏沒有下標運算符,因爲用指針尋址。
請不要啓動一個pascal v.s. C火焰戰爭,這只是一個建議。
如果功課,請標記爲家庭作業。它可能有助於分配一些東西給一個。 – bmargulies 2012-04-27 14:59:34
請注意,如果您需要'n'個實例,則循環條件應該是'i
ysap
2012-04-27 15:00:20
您是否意識到,在您的解決方案中,數組將充滿指向同一實例的指針?你不是真的在那裏複製。 – Raveline 2012-04-27 15:00:41