gpt4 book ai didi

c - c 中未处理的异常

转载 作者:行者123 更新时间:2023-11-30 17:23:37 24 4
gpt4 key购买 nike

我的代码编译良好并执行。但在输入 sortType 值后出现此错误:“ALINUR_CAGLAYAN_LAB6.exe 中 0x52a56af2 (msvcr90d.dll) 处出现未处理的异常:0xC0000005:访问冲突写入位置 0x00000000。”

这是我的代码:

#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 order\n0)Descending order");
scanf("%d", sortType);
sorting(*numbers, &length, &sortType);
printf("The numbers arranged in the order as you entered are given below\n");
for (i = 0; i < length; ++i)
{
printf("%d\n", 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;
}
}

最佳答案

您的代码中存在多个错误。

  • 未定义使用malloc的头文件。
  • scanf 需要访问地址而不是变量。
  • 数组名称会衰减为指针,因此对数组使用 * 是双重解引用
  • 要访问指针中的值,您必须使用 *(解引用指针)。

我已附上更正后的代码。

#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 order\n0)Descending order");
scanf("%d", &sortType);
sorting(numbers, &length, &sortType);
printf("The numbers arranged in the order as you entered are given below\n");
for (i = 0; i < length; ++i)
{
printf("%d\n", 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;
}}

关于c - c 中未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27458523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com