在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]);热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿