edit(fixed): so the error seems to appear because writing a 20 character array will add \0 as a character and become a 21 character array.
I'm trying to detect a char c and remove it from a string char[20] s, but if I wrote a string s of 20 characters exactly, the debug error pops but the code works fine. why does it happen?
#pragma once
#include<iostream>
#include<cstring>
using namespace std;
#pragma warning(disable:4996)
void resultt(char c, char s[]) {
while (*s != '\0') {
if (*s == c) {
strcpy(s,(s 1));
continue;
}
s ;
}
}
void mainn() {
char c; char s[20];
cout << "enter a string : ";
cin >> s;
cout << "enter the character : "; cin >> c;
resultt(c, s);
cout << s;
}
I call that function like this resultt(c,s)
and cout<<s
at last.
CodePudding user response:
the error seems to appear because writing a 20 character array will add \0 as a character and become a 21 character array. by writing for example qwertyuiopqwertyuiop
which is 20 characters, there won't be enough space in the array for the \0 character, so you should write a 19 character word (or less) or increase the array to 21