我正在尝试在C中插入元素程序.我需要将VARIABLE SIZED ARRAY初始化为0,但编译器不允许我这样做.任何出路?
#include <stdio.h>
void insert(int arr[],int k,int pos,int n)
{
display(arr,n);
int i=n-1;
if(pos<n) {
while(i>=pos) {
arr[i]=arr[i-1];
i--;
}
arr[pos]=k;
display(arr,n);
} else {
printf("\n !!Array full!!");
return 0;
}
}
void display(int arr[],int n)
{
int i;
printf("\n Displaying array elements: ");
for(i=0;i<n;i++)
if(arr[i]!=0)
printf("%d ",arr[i]);
}
int main()
{
int n,pos,i=0,k;
char c='y';
printf("\n Enter the no. of elements: ");
scanf("%d",&n);
int arr[n];
printf("\n Enter the array elements: ");
while(c=='y'||c=='Y') {
scanf("%d",&arr[i]);
i++;
printf("\n Continue (y/n): ");
scanf(" %c",&c);
}
c='y';
while(c=='y'||c=='Y') {
printf("\n Enter the element to be inserted: ");
scanf("%d",&k);
printf("\n Enter the position: ");
scanf("%d",&pos);
pos--;
insert(arr,k,pos,n);
printf("\n Continue (y/n): ");
scanf(" %c",&c);
if(c=='n'||c=='N')
printf("\n !!Thank You!!");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试过的时候
int arr[n]={0};
Run Code Online (Sandbox Code Playgroud)
它显示一个错误,无法将可变大小的数组初始化为0.
前卫的输出
输入位置:2
显示数组元素:2 5 3 -344174192
显示数组元素:2 4 5 3
继续(y/n):
...程序以退出代码结束0
按ENTER退出控制台.
垃圾值以粗体显示.
使用memset清除您的数组:
memset(arr, 0x00, sizeof(arr));
当使用带有VLA的sizeof时,sizeof的结果不会在编译时进行评估,因此它非常适合使用.
编辑:虽然您当前的方法有效,但我强烈建议您远离 VLA,以防您需要VLA,使用malloc和free功能.这将显着减少堆栈溢出的变化,当n大数字时.
#include "stdlib.h"
int main() {
int* arr;
int n;
//Get n value by input
arr = malloc(sizeof(*arr) * n);
if (arr == NULL) {
//No memory available, stop program
}
memset(arr, 0x00, sizeof(*arr) * n);
//Do you job here just like before using VLA
//At the end, before returning, call free function
free(arr);
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,VLA代表可变长度阵列.