我有這樣一段代碼:如何操作使用malloc聲明的int數組?
// Returns the fibonacci range until the specified limit
int fibo(int** output, int limit)
{
// Must be 1 or more
if(limit < 1) return 0;
int* range = (int*)malloc(sizeof(int) * limit);
assert(range);
int i;
// Calculate the range
for(i = 0; i < limit; i++)
{
int value;
if(i == 0) value = 0;
if(i == 1) value = 1;
else value = range[i - 2] + range[i - 1];
range[i] = value;
}
*output = range;
return 1;
}
與極限運行它15個輸出
65 1,66,67,133,200,333,533,866,1399,2265, 3664,5929,9593,15522
這是不正確的。我懷疑這是因爲我寫的東西,如range[i - 2]
,當我不應該這樣做。我試圖使用int的大小作爲每個值之間的跳躍,並得到分割錯誤。我正確使用[]
嗎?任何人都可以想到爲什麼我的輸出是奇怪的任何其他原因?
Here's all the code for the program
'range [i-2]'只要'i> 2'就可以。你有沒有嘗試在調試器中逐句通過你的代碼? –
這只是一個簡單的錯誤。仔細考慮一下你的代碼爲'i == 0'做了什麼......(提示:你想要「其他如果」爲第二個手臂) – Nemo
切向注意:'malloc'的規範成語是'int * range = malloc(sizeof (*範圍)*限制)'。不要強制轉換,也不要在'sizeof'中引用硬編碼類型。 –