Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C 数组大小


获取数组大小或长度

要获取数组的大小,可以使用 sizeof 运算符

示例

int myNumbers[] = {10, 25, 50, 75, 100};
printf("%lu", sizeof(myNumbers)); // 打印 20
尝试一下 »

为什么结果显示 20 而不是 5,明明数组包含 5 个元素?

- 因为 sizeof 运算符返回的是类型的**字节大小**。

你在数据类型章节中学过 int 类型通常为 4 个字节,所以上面示例中,4 x 5(4 个字节 x 5 个元素)= 20 个字节

了解数组的内存大小在编写需要良好内存管理的大型程序时非常有用。

但是,当你只想找出数组有多少个元素时,可以使用以下公式(将数组的大小除以数组中第一个元素的大小)

示例

int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);

printf("%d", length);  // 打印 5
尝试一下 »

创建更好的循环

在上一章的数组循环部分,我们把数组大小写在了循环条件中(i < 4)。这并不是理想的做法,因为这只适用于特定大小的数组。

然而,通过使用上面示例中的 sizeof 公式,我们现在可以创建适用于任何大小数组的循环,这更具可持续性。

不要写

示例

int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {
  printf("%d\n", myNumbers[i]);
}
尝试一下 »

最好写成

示例

int myNumbers[] = {25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;

for (i = 0; i < length; i++) {
  printf("%d\n", myNumbers[i]);
}
尝试一下 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.