c - C中的简单数组操作

标签 c arrays

我刚刚用 C 完成了一个简单的数组操作。我已经完成了由许多函数组成的编程,这些函数都在不同的位置执行插入操作。我面临的主要问题是,在我使用 function 执行操作后,控件没有返回到 main 。我找不到原因。只需解释为什么会发生这种情况并为我提供适当的解决方案。我的代码是这样的:

//To insert an element into an already formed array
#include<stdio.h>
#include<stdlib.h>
int binsert(int[],int);
int minsert(int[],int,int);
int einsert(int[],int);
void print(int[],int);
void main()
{
    int a[100],i,j,l,loc;
    printf("Enter the length of the array\n");
    scanf("%d",&l);
    printf("Enter the numbers in the array\n");
    for(j=0;j<l;j++)
    {
        scanf("%d",&a[j]);
    }
    printf("Enter the following options for the operation\n1:insert at the     beginning\n2:insert at specific location\n3:insert at the end\n4:print the array\nAny other key to end the operation\n");
    scanf("%d",&i);
    do
    {   
        switch(i)
        {
             case 1:
                    l=binsert(a,l);
                    break;
             case 2:
                    printf("Enter the location at which you would want to insert(location starts from    1)\n");
                    scanf("%d",&loc);
                    l=minsert(a,loc,l);
                    break;
             case 3:
                    l=einsert(a,l);
                    break;
             case 4:
                    print(a,l);
                    break;
        }
     }while(i==1 || i==2 || i==3 || i==4);
     printf("Operation terminated\n");
     exit(0);
}

int binsert(int a[],int l)
{
    int i;
    for(i=l-1;i>=0;i--)
    {
        a[i+1]=a[i];
    }
    printf("Enter the number to insert\n");
    scanf("%d",&a[0]);
    return (l+1);
}

int minsert(int a[],int loc,int l)
{ 
    int i;
    for(i=l-1;i>=loc;i--)
    {
       a[i+1]=a[i];
    }
    printf("Enter the number to insert\n");
    scanf("%d",&a[loc]);
    return (l+1); 
}

int einsert(int a[],int l)
{
    printf("Enter the number to insert\n");
    scanf("%d",&a[l+1]);
    return (l+1);
}

void print(int a[],int l)
{
    int i;
    printf("The values in the array are as follows\n");
    for(i=0;i<l;i++)
    {
        printf("%d\n",a[i]);
    }
}

最佳答案

问题 1:
你应该做的:

    do
    {   
        printf("Enter the following options for the operation\n1:insert at the     beginning\n2:insert at specific location\n3:insert at the end\n4:print the array\nAny other key to end the operation\n");
        scanf("%d",&i);

        switch(i)
        {
            ....
        }
    }while(i==1 || i==2 || i==3 || i==4);

否则,i 将始终包含相同的值,即 1、2、3、4while(i==1 || i= =2 || i==3 || i==4); 将始终为 true ,因此将无限期地调用相同的函数。

问题 2:检查 l,使其不超过 100,数组的大小。

关于c - C中的简单数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22433739/

相关文章:

objective-c - 将 csv 转换为数据库并绘制数据 : advice on optimisation

c++ - 更改数组大小 C++

javascript - 将列表的数组过滤到jquery中的子数组中

javascript - 如何使用 jquery 或 javascript 从 php 数组中获取值?

C 程序打印垃圾值

c - 我怎样才能将其转换为双向链表?

C:打印。输出是波动的,即它们不遵循模式

c - libuv 简单的 echo 客户端

python - 最小化循环迭代的多变量函数

javascript - 随时间变化的变量数组