[英]Trying to make array size dynamic without use of malloc or calloc or pointers
因此,我嘗試通過在每次循環運行時更新數組大小來根據用戶需要增加數組大小來動態分配 memory,如下面的代碼所示。
正如你在這里看到的,我已經初始化了int score[n];
在開始和 for 循環中,因為我想動態更新數組的大小。 盡管數組大小確實會動態更新,並且我可以在該循環中存儲值(我什至可以打印出這些值),但是當我退出該循環后,所有存儲的數據都變得無用(被銷毀) break;
score[n]
的數組大小再次變為 1,即使我已經給出了 3 個值
#include<stdio.h>
int main()
{
int n=1;
int score[n];
int sum=0;
float average;
for(int i=0;i<n;i++)
{
int score[n];
printf("enter scores\n");
scanf("%d",&score[i]);
int option;
printf("press 1 to add more scores or 0 to exit\n");
scanf(" %d",&option);
if(option==0)
{
printf("The scores are:-\n");
for(int i=0;i<n;i++)
{
printf("%d\n",score[i]);
sum=sum+score[i];
}
average=sum/3.0; // to specify the computer to treat sum also as float I used 3.0
printf("The average is:- %f",average);
break;
}
n++;
}
}
我還分享了調試控制台的屏幕截圖。 這也是我之前輸入的代碼的屏幕截圖。 我上面顯示的代碼是更新的代碼,這只是為了顯示數組大小是如何動態分配的,但在break;
我真的是 C 的新手,有人能告訴我這里到底發生了什么嗎? 如果不允許我再次重新聲明同一個變量,我如何能夠在 for 循環中聲明它而不會出現任何錯誤? 當我們再次初始化同一個變量時究竟發生了什么?
即使在我重新初始化score[n];
大批? 正如您在第二張圖片中看到的那樣,為什么數組的存儲值在循環中斷后被破壞?
謝謝
實際發生的情況是,當您在 for 循環中聲明int score[n]
時,它會分配一個新的 memory 位置,您可以使用printf("%p\n", score);
進行檢查。 ,其scope僅限於 for 循環,因此您可以在該塊(for 循環)中重新聲明。 因此,在“break”被執行並且我們退出循環后,初始int score[n]
自聲明以來沒有改變,因此是一個空數組,因此是您的 output。關於int score[n]
打印和更新其內部代碼環形。 現在關於數組如何動態存儲值,我們知道數組以連續的 memory 存儲值,因此如果空間可用,它將繼續存儲值,請注意您score[i] in scanf() not score[n],
並且由於“i”在每次迭代中不斷增加,因此當我們在 for 循環中聲明int score[n]
時,值不斷添加到 memory 的塊中。 因為,塊是分數數組的相同地址沒有改變(再次檢查printf("%p\n", score);
)因此每次增加'i'它都會將值存儲在數組中。
首先,您的代碼中的問題是for
循環外的score
與for
循環內的score
不同。 如果您嘗試像您那樣在 for 循環之外“重新聲明” score
,您的程序將無法編譯。 當您退出 for 循環時,您一直在處理的樂譜將被刪除,就像在每次循環迭代中一樣。
你在欺騙自己相信你的分數數組沒有被重置,因為你很幸運地得到了 memory,但是測試你的代碼時我不時得到隨機值。
enter scores
45
press 1 to add more scores or 0 to exit
1
enter scores
46
press 1 to add more scores or 0 to exit
1
enter scores
47
press 1 to add more scores or 0 to exit
1
enter scores
48
press 1 to add more scores or 0 to exit
1
enter scores
50
press 1 to add more scores or 0 to exit
1
enter scores
52
press 1 to add more scores or 0 to exit
0
The scores are:-
4
0
626127794
21878
50
52
動態更改數組大小必須使用指針malloc 和 realloc來完成,我強烈建議您學習如何使用它們。
如果您想從更簡單的開始:為什么不在開始時將數組的大小設置為較大的值(比如 1000)並防止用戶輸入超過該值的值?
另一方面, average = sum/3.0;
應該是average = sum/(float)n;
快樂學習
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.