Reputation: 25
I already looked with a debugger and i get this error when it leaves the main() function. Here's my Code:
#include <iostream>
char * trim(const char * _str) {
char * newString = new char;
for (int i = 0; i < 10; i++) {
newString[i] = _str[i];
}
newString[10] = '\0';
return newString;
}
int main() {
std::cout << trim("This is a test");
return 0;
}
Thanks for your help.
Upvotes: 0
Views: 54
Reputation: 50210
you error is this
#include <iostream>
char * trim(const char * _str) {
char * newString = new char; <<<<==== you allocate one character
for (int i = 0; i < 10; i++) {
newString[i] = _str[i]; <<<<=== but try to write a whole string
}
newString[10] = '\0';
return newString;
}
int main() {
std::cout << trim("This is a test");
return 0;
}
not sure what you are trying to do but this will work
#include <iostream>
char * trim(const char * _str) {
char * newString = new char[strlen(_str) + 1];
for (int i = 0; i < 10; i++) {
newString[i] = _str[i];
}
newString[10] = '\0';
return newString;
}
int main() {
std::cout << trim("This is a test");
return 0;
}
really you should use
std::string
for strings in a c++ programstd::vector
for arrays of things created on the flyUpvotes: 1