C语言 在数组中插入元素-

vlf7wbxs  于 2023-03-01  发布在  其他
关注(0)|答案(1)|浏览(137)

我不太擅长C语言,所以请帮助我完成这个项目,我希望用户选择他想要执行的操作,我刚刚完成了插入部分,这里的代码在插入后给出了垃圾值。

#include<stdio.h>
#include<stdlib.h>

int main(){
    int n, opt, i, insOpt, pos, newEle;
    printf("Enter the number of elements you want to store in the array: ");
    scanf("%d", &n);
    int* arr = (int*) malloc(n*sizeof(int));
    printf("Enter all %d elements you want to store in the array: ", n);
    for(i=0; i<n; i++){
        scanf("%d", &arr[i]);
    }

    options:
    printf("Enter the operation you want to perfrom: \n 1. Insertion \n 2. Deletion \n 3. Traversing \n 4. Searching \n 5. Sorting \n 6.Reverse of array \n");
    scanf("%d", &opt);
    switch (opt)
    {
    case 1:
        n++;
        int* newArr=(int*) realloc(arr, n*sizeof(int));
        for(i=0; i<n-1; i++){
            newArr[i] = arr[i];
        }
        free(arr);
        arr = newArr;
        printf("Pick where you want to insert: \n 1. Beginning \n 2. Middle \n 3. End \n 4. Position");
        scanf("%d", &insOpt);
        switch (insOpt)
        {
        case 1:
            pos=0;
            break;
        case 2:
            //
            break;
        case 3:
            pos=n;
            break;
        case 4:
            printf("Enter the position: ");
            scanf("%d", &pos);
            break;
        default:
            printf("Please pick between 1 to 4: ");
            break;
        }
        printf("Enter the element: ");
        scanf("%d", &newEle);
        for(i=n-1; i>=pos-1; i--){
            arr[i]=arr[i-1];
        }
        arr[pos-1] = newEle;
        printf("Array after insertion: ");
        for(i=0; i<n; i++){
            printf("%d ",arr[i]);
        }
        break;
    
    default:
        break;
    }

    return 0;
}

现在,当我尝试在开始插入元素时,它会给我一些8后面的随机值-
插入后的阵列:8 1512474568 5 1571285629 1432712575 3

e5nszbig

e5nszbig1#

对于初学者,此代码片段

for(i=0; i<n-1; i++){
        newArr[i] = arr[i];
    }
    free(arr);

没有意义。重新分配的数组已经包含现有元素,并且指针arr在本例中无效。因此请删除此代码段。
如果用户选择了结束位置,则pos的值应为n - 1,而不是n。另一方面,如果用户选择了阵列开头的位置,则pos应等于0。
在这种情况下,下面的for循环如下所示

for ( i=n-1; i != pos; i--){
        arr[i] = arr[i-1];
    }
    arr[pos] = newEle;

相关问题