Reputation: 1353
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 appreciated.
Upvotes: 3
Views: 2341
Reputation: 76500
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];
Upvotes: 0
Reputation: 129403
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? :)
Upvotes: 0
Reputation: 44298
std::string being a nice implementation of a vector of chars :)
Upvotes: 0
Reputation: 355059
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.
Upvotes: 5