【发布时间】: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;
}
驱动程序
【问题讨论】:
-
由于您不验证
pos或num的值,因此无法判断您需要基于0 还是基于1 的pos和num,现在有办法给出一个具体的答案。虽然您同时使用pos和num可以尝试访问低于0和高于n。验证每个用户输入(例如if (scanf ("%d", &pos) != 1) { /* handle error */ })并验证每个输入是否在要求的范围内(例如if (pos < 0 || n <= pos) { /* handle invalid pos * }) -
另外,不要使用古老的 DOS 标头
conio.h。如果您需要在 Windows 上保持终端打开,只需使用getchar()。conio.h100% 不可移植到 DOS 或 Windows 以外的任何地方。 -
我不确定
#include<conio.h>是否还在使用,最好使用最新的编译器
标签: c++ arrays c data-structures