C++ Char without Limit
I'm pretty well versed in C#, but I decided it would be a good idea to learn C++ as well. The only thing I can't figure out is chars. I know you can use the string lib but I also want to figure out chars.
I know you can set a char with a limit like this:
#include <iostream>
using namespace std;
int main()
{
char c[128] = "limited to 128";
cout << c << endl;
system("pause");
return 0;
}
But how would I make a char without a limit? I've seen chars with * but I though that was for pointers. Any help is greatly appr开发者_StackOverflow中文版eciated.
You can't have an array without limit. An array occupies space in memory, and sadly there is no such thing as limitless memory.
Basically, you have to create an array of a certain size and write logic to expand the size of the array as you need more space (and possibly shrink it as you need less space).
This is what std::string
and std::vector
do under the hood for you.
You can use a vector
of char
.
std::string being a nice implementation of a vector of chars :)
A datastructure needs memory allocated for it.
Some datastructures (such as string, or a vector of chars) have internal logic in their class which allocates memory as needed dynamically.
Arrays (which come from C) do not - you need to allocate memory for them manually, by either static way (char c[128]) as your example does, or dynamically at runtime via malloc() and company. Of course, to do the dynamic allocation/reallocation right is not very simple and why bother doing it when there already are classes (e.g. string) that do it for you the right way? :)
C/C++ char
arrays are just about identical to char*
. The same block of code can be rewritten as:
int main()
{
char* c = "limited to 128";
cout << c << endl;
system("pause");
return 0;
}
The compiler will generate a null terminated string for you that you could use throughout your code. The way to do it dynamically would be to either use malloc
or operator new []
.
char* str = malloc(sieof(char) * requiredlength); //C-compatible
OR
char* str = new char[requiredlength];
精彩评论