P
P
parkito2014-10-09 23:17:20
C++ / C#
parkito, 2014-10-09 23:17:20

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

But the number of elements can be too large or small.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
[
[email protected]><e, 2014-10-10
@barmaley_exe

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.

E
Espleth, 2014-10-10
@Espleth

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(); //количество символов

Further we work as with a normal array.

S
Sergey, 2014-10-09
Protko @Fesor

in the context of the task, lists look more appropriate ... (usual such lists on pointers). Or realloc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question