【问题标题】:array operations facing problem with change in size of array after insertion and after performing one operation loop exit数组操作在插入后和执行一个操作循环退出后面临数组大小变化的问题
【发布时间】:2020-11-08 06:24:59
【问题描述】:
***头文件*** 请帮助我找出错误,为什么我的代码在我的指令之前退出

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

显示

为什么在遍历数组元素时没有数组元素没有改变所有初始元素都只打印出来

  int display_array(int arr[], int n)
    {
        int i;
        for (i = 0; i < n; i++)
        {
            printf("arr[%d] = %d\n", i, arr[i]);
        }
        return 0;
    }

插入

   int insert_position(int arr[], int n)
    {
        int i = 0, pos, num;
        printf("Enter the number to be inserted:\n");
        scanf("%d", &num);
        printf("enter the pposition at which the number is to be inserted:\n");
        scanf("%d", &pos);
        for (i = n - 1; i >= pos; i++)
        {
            arr[i + 1] = arr[i];
        }
        arr[pos] = num;
        n = n + 1;
        return 0;
    }

删除

 int delete_position(int arr[], int n)
    {
        int i = 0, pos;
        printf("Enter the position from which the number has to be deleted:\n");
        scanf("%d", &pos);
    
        for (i = pos; i < n - 1; i++)
        {
            arr[i] = arr[i + 1];
        }
        n = n - 1;
        return 0;
    }

驱动程序

【问题讨论】:

  • 由于您不验证posnum 的值,因此无法判断您需要基于0 还是基于1 的posnum,现在有办法给出一个具体的答案。虽然您同时使用posnum 可以尝试访问低于0 和高于n。验证每个用户输入(例如if (scanf ("%d", &amp;pos) != 1) { /* handle error */ })并验证每个输入是否在要求的范围内(例如if (pos &lt; 0 || n &lt;= pos) { /* handle invalid pos * }
  • 另外,不要使用古老的 DOS 标头 conio.h。如果您需要在 Windows 上保持终端打开,只需使用 getchar()conio.h 100% 不可移植到 DOS 或 Windows 以外的任何地方。
  • 我不确定#include&lt;conio.h&gt;是否还在使用,最好使用最新的编译器

标签: c++ arrays c data-structures


【解决方案1】:

我认为您在这些函数中将这些参数作为按值传递,而不是按引用传递。这就是为什么每次调用它们时都会打印初始值的原因。 可以使用指针,也可以使用全局变量来获得想要的结果。

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2015-05-13
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多