c - 在c 中,未处理的异常

  显示原文与译文双语对照的内容
0 0

我的代码编译得很好,并且执行。 但是,在输入sortType值后,会出现这里错误: " 0 x52a56af2 ( msvcr90d.dll ) 中未处理的异常: 0 xC0000005: 写入位置 0 x00000000时发生访问冲突。"

这是我的代码:

#include <stdio.h>
int sorting(int *liverpool8, int *besiktas0, int *hahaha);
void main()
{
 int *numbers;
 int length;
 int sortType=0;
 int i;
 printf("Enter the length of array:");
 scanf("%d",&length);
 numbers = (int*)malloc(length*sizeof(int));
 for (i = 0; i <length; ++i)
 {
 printf("%d. element:", i+1);
 scanf("%d", &numbers[i]);
 }
 printf("nPlease select one of the following functions:n1)Ascending ordern0)Descending order");
 scanf("%d", sortType);
 sorting(*numbers, &length, &sortType);
 printf("The numbers arranged in the order as you entered are given belown");
 for (i = 0; i <length; ++i)
 {
 printf("%dn", numbers[i]);
 }
 system("pause");
}
int sorting(int *numbers, int *length, int *sortType)
{ 
 int j, i, a;
 if(sortType == 1)
 {
 for (i = 0; i <length; ++i)
 {
 for (j = i + 1; j <length; ++j)
 {
 if (numbers[i]> numbers[j])
 {
 a = numbers[i];
 numbers[i] = numbers[j];
 numbers[j] = a;
 }
 }
 }
 }
 else if(sortType == 0)
 {
 for (i = 0; i <length; ++i)
 {
 for (j = i + 1; j <length; ++j)
 {
 if (numbers[i] <numbers[j])
 {
 a = numbers[i];
 numbers[i] = numbers[j];
 numbers[j] = a;
 }
 }
 }
 return *numbers;
 }
}
时间:原作者:4个回答

0 0

你的代码中有多个错误。

  • 使用 malloc的头文件没有定义。
  • scanf 需要访问地址而不是变量。
  • array 名称衰变为指针,因此使用 * 进行 array 是双重取消引用
  • 要访问指针中的值,你必须使用 *,dereferencing指针。

我已经把修正后的代码。

#include <stdio.h>
#include <stdlib.h>
int sorting(int *liverpool8, int *besiktas0, int *hahaha);
void main()
{
int *numbers;
int length;
int sortType=0;
int i;
printf("Enter the length of array:");
scanf("%d",&length);
numbers = (int*)malloc(length*sizeof(int));
for (i = 0; i <length; ++i)
{
 printf("%d. element:", i+1);
 scanf("%d", &numbers[i]);
}
printf("nPlease select one of the following functions:n1)Ascending ordern0)Descending order");
scanf("%d", &sortType);
sorting(numbers, &length, &sortType);
printf("The numbers arranged in the order as you entered are given belown");
for (i = 0; i <length; ++i)
{
 printf("%dn", numbers[i]);
}
system("pause");
}
int sorting(int *numbers, int *length, int *sortType)
{ 
int j, i, a;
if(*sortType == 1)
{
for (i = 0; i <*length; ++i)
{
 for (j = i + 1; j <*length; ++j)
 {
 if (numbers[i]> numbers[j])
 {
 a = numbers[i];
 numbers[i] = numbers[j];
 numbers[j] = a;
 }
 }
}
}
else if(sortType == 0)
{
for (i = 0; i <*length; ++i)
{
 for (j = i + 1; j <*length; ++j)
 {
 if (numbers[i] <numbers[j])
 {
 a = numbers[i];
 numbers[i] = numbers[j];
 numbers[j] = a;
 }
 }
}
return *numbers;
}}
原作者:
...