字符串的访问冲突读取位置和错误读取字符 [英] Access violation reading location and error reading character of string
问题描述
谁能解释为什么会抛出访问冲突读取位置错误以及为什么在 a[] 中我得到错误读取字符串的字符"?我有两个字符串,必须从包含其他字符串的第一个字符串中删除所有单词.我做错了什么?
Who can explain why access violation reading location erorr is thrown and why in a[] i get "erorr reading characters of string"? I have two strings and must to remove all words from first string that containing other string. What i do wrong?
#include "stdafx.h"
#include<iostream>
#include<cstring>
using namespace std;
char s1[100] = {};
char s2[100] = {};
void Words(char s1[], char s2[]) {
int k = 0;
char*p1 = nullptr;
char*np1 = nullptr;
char*p2 = nullptr;
char*np2 = nullptr;
char *m[20];
char *a[20];
char s3[100] = {};
for (int i = 0; i < 20; i++) {
char n[50] = {};
char l[50] = {};
m[i] = n;
a[i] = l;
}
char delimeter[] = " ,.!?;:";
p2 = strtok_s(s2, delimeter, &np2);
while (p2 != nullptr) {
strcpy(a[k], p2);
k++;
p2 = strtok_s(nullptr, delimeter, &np2);
}
k = 0;
p1 = strtok_s(s1, delimeter, &np1);
while (p1 != nullptr) {
strcpy(m[k], p1);
k++;
p1 = strtok_s(nullptr, delimeter, &np1);
}
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (strcmp(m[i], a[j]) != 0 && m[i] != 0 && a[j] != 0) {
strcat(s3, m[i]);
}
}
}
puts(s3);
for (int i = 0; i < 20; i++) {
delete m[i];
delete a[i];
}
}
主要功能:
int main()
{
gets_s(s1);
gets_s(s2);
Words(s1, s2);
return 0;
}
推荐答案
这里至少有一个问题:
for (int i = 0; i < 20; i++) {
char n[50] = {};
char l[50] = {};
m[i] = n;
a[i] = l;
}
在循环之后 m
和 a
的所有元素都指向超出范围的变量.一旦离开 for
循环的 {}
之间的范围,变量 n
和 l
就不再存在.
After that loop all elements of m
and a
point to variables that have gone out of scope. The variables n
and l
cease to exist once the scope between the {}
of the for
loop has been left.
您对指针有很多误解,您可能应该阅读一些关于 C 语言的好书(您编写的代码实际上比 C++ 更像 C).
You have many misconceptions about pointers and you should probably read some good book about the C language (the code you wrote is actually more C than C++).
肯定有更多错误.
这篇关于字符串的访问冲突读取位置和错误读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!