array

hi. wanna know if i can have an array with unlimited value or not.
s.th like this:

int a;
cin>>a;
char b[a];

in which i can let the user choose how long his/her input is gonna be.

PS: i wanna write a program in which the user enters a text and the program changes the text into binary code (using switch-case~...) so user should be free in writing his/her text as long as s/he wants.
Look into either using a string (preferred), or a vector (if you have to).

No, you cant.

You could also allocate memory using the new operator.

1
2
3
4
	// allocate memory
	char *b = new char[a];
	// free memory
	delete[] b;
Which is a very bad idea, because you'll end up with memory leaks, so if you're going to do that, look at std::unique_ptr and std::shared_ptr. And yes, you can, because vectors are dynamically sized arrays, but if you want a dynamically sized char array, then std::string is better.

Since when has memory allocation been a very bad idea, memory leaks are down to coding errors not the fact I choose to allocate memory in the first place.

I do agree with your vector comment and suggestion, and my post was not a disagreement in the slightest, but merely an alternative if that was the path he wants to take.

EDIT: by the way, just read over you post again and my comment "No you cant" was at the O/P not you, just so you are aware.
Last edited on
I'm not saying memory allocation is a bad idea, I'm saying naked news are a bad idea. In order to absolutely definitely avoid all memory leaks, code becomes long and unwieldy, as opposed to just declaring points as unique_ptrs and shared_ptrs which can just be initialised and forgotten about.

Which is a very bad idea, because you'll end up with memory leaks


Yes you did, anyway.. my answer "no you cant" was not pointed at you so judging by your reaction you felt it was:

And yes, you can, because vectors are dynamically sized arrays


My post was not in disagreement with yours in any way shape or form. Vectors are indeed a very good solution.
Topic archived. No new replies allowed.