C ++ Char without restriction

I am pretty good at C #, but I decided that it would be nice to also learn C ++. The only thing I canโ€™t understand is the characters. I know you can use the lib string, but I also want to figure out the characters.

I know that you can set char with a limit as follows:

#include <iostream> using namespace std; int main() { char c[128] = "limited to 128"; cout << c << endl; system("pause"); return 0; } 

But how can I make char without restriction? I saw characters with *, but although that was for pointers. Any help is appreciated.

+4
source share
5 answers

You can use vector for char .

+2
source

You cannot have an array without limits. An array takes up space in memory, and, unfortunately, there is no such thing as unlimited memory.

Basically, you need to create an array of a certain size and write logic to expand the size of the array, since you need more space (and possibly reduce it because you need less space).

This is what std::string and std::vector do under the hood for you.

+6
source

std :: string is a good implementation of character vector :)

0
source

A data structure requires memory allocated for it.

Some data structures (such as a string or character vector) have internal logic in their class that allocates memory dynamically as needed.

Arrays (which come from C) are not needed - you need to allocate memory for them manually, either in a static way (char c [128]), as your example, or dynamically at runtime via malloc () and company, of course, make the correct allocation / redistribution of rights is not very simple and why you need to do this when there are already classes (for example, a string) that do this for you in the right way? :)

0
source

C / C ++ char arrays are roughly identical to char* . The same code block can be rewritten as:

 int main() { char* c = "limited to 128"; cout << c << endl; system("pause"); return 0; } 

The compiler will create a zero-terminated string for you that you can use in all of your code. The way to do this dynamically is to either use malloc or operator new [] .

 char* str = malloc(sieof(char) * requiredlength); //C-compatible 

OR

 char* str = new char[requiredlength]; 
0
source

Source: https://habr.com/ru/post/1308316/


All Articles