Answer the question
In order to leave comments, you need to log in
The code works, but at the end throws "Debug Error", why?
Task: Write a function that adds another space next to a space (the case where two or more spaces in a row are not taken into account). The function must take a string (an array of characters) as arguments. The function must return the newly formed string.
In general, the program works, but at the end there is such a sign:
CODE:
#include "pch.h"
#include <iostream>
#include <Windows.h>
void add_spaces(char* a)
{
int count = 0;
for (int i = 0; i < strlen(a); i++)
{
if (a[i] == ' ')
count++;
}
char* new_arr = new char[strlen(a) + count];
for (int i = 0, j = 0; i < strlen(new_arr); i++, j++)
{
if (a[j] == ' ')
{
new_arr[i] = ' ';
new_arr[i + 1] = ' ';
i++;
}
new_arr[i] = a[j];
}
for (int i = 0; i < strlen(new_arr); i++)
{
std::cout << new_arr[i];
}
delete[]new_arr;
}
int main()
{
using namespace std;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
char a[] = " ";
cout << "Введите строку: ";
cin.getline(a, 128);
cout << "\nСтрока после добавления пробелов: ";
add_spaces(a);
}
Answer the question
In order to leave comments, you need to log in
After allocating memory, you have garbage in the new_arr array, and you call the strlen(new_arr) function to calculate the length of the string with garbage in memory. This function does not work correctly, it gives a value that does not correspond to reality. Then you fill in the memory you didn't allocate (in new_arr[i]). When you try to delete it using delete[] you get heap corrupt.
PS. using c++ use std::string
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question