在C中初始化可变大小的数组
可变大小的数组是数据结构,其长度是在运行时而不是编译时确定的。这些数组在简化数值算法编程中很有用。C99是一种C编程标准,允许使用可变大小的数组。
演示C语言中可变大小数组的程序如下所示-
示例
#include
int main(){
int n;
printf("Enter the size of the array: \n");
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[]是上述程序中的可变大小数组,因为其长度在运行时由用户提供的值确定。显示此代码段如下所示:
int n;
printf("Enter the size of the array: \n");
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]);热门推荐
10 新年过后奋斗祝福语简短
11 离校退群祝福语简短
12 女生成年祝福语简短
13 友谊晚上祝福语大全简短
14 春季祝福语女生文案简短
15 开店大吉文案祝福语简短
16 美丽晚霞祝福语简短句
17 同事有趣祝福语大全简短
18 空军大学开学祝福语简短