tags:

views:

190

answers:

5

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.

+4  A: 

You can use a vector of char.

codaddict
You could... But I'm guessing that doesn't really fit the spirit of what Lienau's looking for, since that would break line 7 of the code presented.
Mac
@Mac: He does not want to use std::string or pointers and still wants to work with bare char without limits.
codaddict
+4  A: 

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.

James McNellis
+1 short, complete answer
BlueRaja - Danny Pflughoeft
A: 

std::string being a nice implementation of a vector of chars :)

Keith Nicholas
A: 

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? :)

DVK
A: 

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];
Igor Zevaka
What's wrong with `vector`? I see no purpose in doing the allocations by hand.
GMan
Nothing, my impression was that it was an obvious alternative to the OP, hence the bare bones version.
Igor Zevaka