Answer the question
In order to leave comments, you need to log in
How to organize a dynamic character array in c++?
Hello, please help me with the following question.
It is necessary for me that all characters from a file or entered by the user were located in an array. I think you need to use a dynamic array for this. But I can't figure out how. Somehow you need to count the number of characters --> allocate memory --> initialize the array. comes to mind
#include<iostream>
#include<cstdlib>
int main()
{
char *arr;
int size;
setlocale(LC_ALL, "Russian");
std::cout<<"Введите размер массива :"<<std::endl;
std::cin>>size;
arr = new char[size];
std::cout<<"Заполните массив :"<<std::endl;
for (int i = 0; i < size; i++)
std::cin>>arr[i];
std::cout<<std::endl;
for (int i = 0; i < size; i++)
std::cout<<" "<<arr[i];
delete [] arr;
}
Answer the question
In order to leave comments, you need to log in
In the general case, it is impossible to predict how many elements will be in the array (you can estimate this value from above, but it can be extremely uneconomical), so the concept of expanding arrays is used: there is a pre-allocated array of a given size, which is filled as the program runs. As soon as the array is full and there is no more space, but one more element needs to be inserted, a new array of larger capacity is created, the contents of the old one are copied there, and the element is inserted into the new array. The old one is then removed.
This is how std::vector is implemented, for example.
You can use, as written above, vectors.
It looks like this:
#include <vector> //понадобится include
vector<char> arr; //объявляем его. длину вводить не обязательно
char c;
cin >> c;
arr.push_back(c); //вводим элементы
int length = arr.size(); //количество символов
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question