我刚刚编译了这段代码,它向我展示了这个错误:
Sample7.exe中的0x0F2FC4DA(ucrtbased.dll)抛出异常:0xC0000005:访问冲突读取位置0x97979436。
我真的不知道这个错误意味着什么,因为我刚刚使用C几个月。我也尝试在任何其他网站上寻找帮助,但我没有找到任何帮助。
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int i = 0, n, length = 0;
char *abc;
printf("\n Enter size of array: ");
scanf_s("%d", &n);
abc = new char[n];
printf("\n Enter symbols: ");
scanf_s("%s", abc);
length = strlen(abc);
for (i = 0; i <= n; i++)
{
printf("\n Your array: ", abc);
while (length = 10)
{
if (abc[i] >= 'A' && abc[i] <= 'Z')
{
abc[i] = ' ';
}
printf("\n Your array after deleting A-Z symbols",abc);
}
}
delete[]abc;
_getch();
return 0;
答案 0 :(得分:0)
您收到此错误是因为您正在从分配的空间中访问内存。我的猜测是你正在访问它的边界的char数组索引。你需要逐行调试你的代码,看看这发生了什么。
在代码的第一眼看来,我发现了以下错误。
for (i = 0; i <= n; i++)
我想你的意思是:
for (i = 0; i < n; i++)
while (length = 10)
也应为while (length == 10)
答案 1 :(得分:0)
首先,您的主要罪魁祸首是scanf_s("%s", abc);
,因为当您通过scan_f
读取字符串时,您需要提供字符串的大小,如scanf_s("%s", abc, n);
。
此外,您的代码中也需要进行少量更正。您可以从consul输入数组的大小。例如Enter size of array: 10
,你在这里输入了10。现在数组的大小是10,因此你的循环应该从0到9总共10位继续,因此你的for循环应该是for (i = 0; i <= n; i++)
。第二个你的while循环while (length = 10)
这将永远为真,因此它变成一个无限循环。因此它应该是while (length = 10)
,但你甚至根本没有这个循环。第3个你的printf语句1st应该是printf("\n Your array: %s", abc);
而第二个应该是printf("\n Your array after deleting A-Z symbols %s ",abc);
但是这个语句应该在delete语句之后的程序结尾。
我已在下面更正了您的计划。试试这个: -
#include "stdafx.h"
#include "stdafx.h"
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int i = 0, n, length = 0;
char *abc;
printf("\n Enter size of array: ");
scanf_s("%d", &n);
abc = new char[n];
printf("\n Enter symbols: ");
scanf_s("%s", abc, n);//your scanf_s function was wrongly define.This one is correct.
printf("\n Your array1: %s", abc);
for (i = 0; i < n; i++)
{
printf("\n Your array: %s", abc);
//while (length == 10) You don't need this while loop at all
//{
if (abc[i] >= 'A' && abc[i] <= 'Z')
{
abc[i] = ' ';
}
//}
printf("\n Your array after deleting A-Z symbols :%s", abc);
}
delete[]abc;
_getch();
return 0;
}