Answer the question
In order to leave comments, you need to log in
Extra characters in c++, where?
There is a code:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
char* reverse ( char *str )
{
int length_str = strlen(str);
char *str2 = new char[length_str];
for(int i=0;i<length_str;i++)
str2[i]=str[length_str-i-1];
return str2;
}
int main()
{
setlocale(LC_ALL,"RUS");
char *array = new char;
cin>>array;
cout <<"Исходная строка > "<< array << endl;
char *str = reverse(array);
cout <<"Перевернутая строка > "<< str<< endl;
system("Pause");
}
Answer the question
In order to leave comments, you need to log in
First, it new char
will allocate memory for only one character, and you have a lot of them. That is, in the next line (cin >> array)
, travel through memory. If you write for learning purposes and you can’t take std::string
, then allocate with a margin, for example, new char[256];
you will need to free up memory with the help of delete[] array
;
Secondly, the end of the string is determined by the null character at the end. cin >> array
does it itself (writes a null character at the end of array), and you do not set a null character in your function. You can do it like this:
But you need to keep in mind that you need to allocate memory [at least] 1 more than length_str
.
Total:
1. In both cases, you need to allocate memory for an array. In the first case it is possible under 256 elements. Ideally, at the same time, read not with cin, but with other functions, in order to avoid overflow in case a longer string is entered.
2. In reverse, you need to set a terminating zero and correct the length of the array. It is possible to expand a string in place, i.e. swap letters, and not create a new line (in this case, you do not need to allocate memory or touch the terminating zero, it will remain in place).
3. You need to delete the allocated memory at the end of use withdelete []
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question