[英]How to initialise an variable sized int array to 0 in C?
我正在尝试在 C 中插入元素程序。在那里我需要将一个可变大小的数组初始化为 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;
}
当我尝试
int arr[n]={0};
它显示了一个错误,无法将可变大小的数组初始化为 0。
程序的输出
输入位置:2
显示数组元素:2 5 3 -344174192
显示数组元素:2 4 5 3
继续(是/否):
...程序以退出代码 0 结束
按 ENTER 退出控制台。
垃圾值以粗体显示。
使用memset
清除数组:
memset(arr, 0x00, sizeof(arr));
将 sizeof 与 VLA 一起使用时,不会在编译时评估 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);
}
仅供参考, VLA代表可变长度数组。
所以,我最后的代码片段如下
#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];
memset(arr, 0x00, sizeof(arr[0]) * 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.