Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

c++ - Access violation reading location and error reading character of string

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];
  }
}

Main function:

int main()
{
  gets_s(s1);
  gets_s(s2);
  Words(s1, s2);
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is at least one problem here:

  for (int i = 0; i < 20; i++) {
    char n[50] = {};
    char l[50] = {};
    m[i] = n;
    a[i] = 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.

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++).

There are certainly more errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...