在 C 中初始化变长数组
变长数组是其长度在运行时而不是编译时确定的数据结构。这些数组有助于简化数值算法编程。C99 是一种允许变长数组的 C 编程标准。
如下所示,使用 C 示范变长数组的程序:
示例
#include
int main(){
int n;
printf("Enter the size of the array:
");
scanf("%d", &n);
int arr[n];
for(int i=0; i<n; i++)
arr[i] = i+1;
printf("The array elements are: ");
for(int i=0; i<n; i++)
printf("%d ", arr[i]);
return 0;
}输出
上述程序的输出如下所示:
Enter the size of the array: 10 The array elements are: 1 2 3 4 5 6 7 8 9 10
现在,让我们了解一下上述程序。
在上述程序中,数组 arr[] 是一个变长数组,因为其长度是由用户提供的 run time 值确定的。展示此操作的代码段如下所示:
int n;
printf("Enter the size of the array:
");
scanf("%d", &n);
int arr[n];数组元素使用 for 循环初始化,然后显示这些数组元素。展示此操作的代码段如下所示:
for(int i=0; i<n; i++)
arr[i] = i+1;
printf("The array elements are: ");
for(int i=0; i<n; i++)
printf("%d ", arr[i]);
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP