自创C语言对数组进行插入的函数

指导思想:模拟python中对list的insert操作,快速向C程序数组(一维)插入新的元素

实参:
①数组首元素地址(指针型变量):对某一数组进行操作,需先找到这个数组在内存中的地址
②需要插入的位置(整数型变量):采用下标法记录,即从0开始计数
③插入的值(与被插入数组类型一致的变量),暂时将被插入数组限制为整数型数组

起草函数:insert_arr(int * pArr, int loca, int val);

实现途径:从被插入元素下标起,依次向后移动一位
Do pArr[n] = pArr[n-1];
While n-1 > loca;
【健壮性问题:应该判断loca是否为负数或者超出数组元素个数】
If loca < 0 or loca > n;
Return false;
End;
产生新的问题:insert_arr如何判断loca是否越界,也就是n的值从何而来?
应该向insert_arr函数多传递一个参数:len(即数组长度)
自此,函数更新为

insert_arr(int * pArr, int len, int loca, int val);

尝试写出函数:
int insert_arr(int * pArr, int len, int loca, int val)
{
If(loca > 0 && loca <= len-1)//数组下标最大值=数组长度-1
{
Int count;
For(count = len - 1; count >= loca; count–)
{
*pArr[count] = *pArr[count - 1];
/产生新问题:这样操作当且仅当该数组最后一个元素存储的是垃圾数字时不会影响所需数组的存储。但当数组最后一个元素也是被我们所需要的元素时,这样会将它删去(准确来说是被倒数第二个元素覆盖),暂时先不管,实现主要代码先/
}
*pArr[loca] = val;//将val的值覆盖原来的值,即插入
}
Else
{
Return -1;//此值用来标志插入失败
}
}

实际代码编写如下:

# include <stdio.h>
# include <stdlib.h>
int insert_arr(int * pArr,int len, int loca, int val);
void prt_arr(int * pArr, int len);
int main(void)
{
    
    
    int fake_length, location, value;
    printf("Please input the length of the array u wanna have:");
    scanf("%d",&fake_length);
    int *Arr = (int *)malloc(sizeof(int) * fake_length);
    for(int count=0; count<fake_length; count++)
    {
    
    
        Arr[count] = count;
    }
    //initialize the array
    
    if(Arr != NULL)
    {
    
    
        printf("Please input the value u wanna insert:");
        scanf("%d",&value);
        printf("Please input the location u wanna insert:");
        scanf("%d",&location);
        int status = insert_arr(Arr, fake_length, location, value);
        if(status == -1)
        {
    
    
            printf("Function ran failed!\nPlease check the data u input!\n");
        }
        else if(status == 1)
        {
    
    
            printf("Function ran sucessfully!\nCheers!!!\n");
            prt_arr(Arr, fake_length);
        }
        else
        {
    
    
            printf("There is an unknow problem...\n");
        }
    }
    else
    {
    
    
        printf("Sooooorry~System denied ur application of memory!\n");
    }
}
int insert_arr(int *pArr, int len, int loca, int val)
{
    
    
    if(loca >= 0 && loca <= len - 1)
    {
    
    
        int count;
        for(count = len - 1; count > loca; count--)
        {
    
    
            pArr[count] = pArr[count-1];
            //review the point used as array without of '*'
        }
        pArr[loca] = val;
        return 1;
    }
    else
    {
    
    
        return -1;
    }
}
void prt_arr(int * pArr, int len)
{
    
    
    for(int count = 0; count<len; count++)
    {
    
    
        printf("%d\t",pArr[count]);
    }
    printf("\n");
    printf("Thanks for u used\n");
    free(pArr);
}

产生新的问题:数组的最后一个元素被抹去了【待解决】

猜你喜欢

转载自blog.csdn.net/weixin_43888800/article/details/113116710