N
N
Nikita Kochetkov2015-05-26 15:45:17
C++ / C#
Nikita Kochetkov, 2015-05-26 15:45:17

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");
 }

After launch, it gives the following:
3345fd2d964f4ce58017641d6f730881.png
Where do these characters in the reversed string come from? And how to remove them?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Ruchkin, 2015-05-26
@fiercekilla

First, it new charwill 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 >> arraydoes 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 []

V
Vladimir Martyanov, 2015-05-26
@vilgeforce

The null character at the end of the string is gone...

A
Antony, 2015-05-26
@RiseOfDeath

A string (in addition to the std::string class) in C/C++ is a char array terminated by a null character. (0x00 or '\0'). All standard string manipulation tools treat such a character as the end of a string. And you moved it at all to the beginning.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question