Char Array Size Problem
So I'm trying to make a program, Which has nothing to do with the topic.
But I ran into a problem.
I need to get a char array size of 6 doing:
but the size (6) is undefined until user input.
So I need to do char myChar[var]; (Var being 6 for now).
When I do:
Yay! It works!!!
But when I do:
int val = 6;
It doesn't work.
Why is this and how can I fix it???
if you want to create the array at runtime then you need a dynamic array.
char *myChar = new char[val];
using namespace std;
#define var 6
should work fine
in C++ you have lots of options. A std::vector is perhaps easiest and safest to use. A std::string is also possible here. Once allocated, the syntax for accessing elements is the same for each.
std::cout << "enter array size: ";
std::cin >> var;
char * myChar = new char[var]; // dynamic character array of length var
std::string myString(var, ' '); // string of length var, filled with spaces
std::vector<char> myVec(var); // vector of length var
myChar = myString = myVec = 'A'; // put something in first element
std::cout << myChar << std::endl;
std::cout << myString << std::endl;
std::cout << myVec << std::endl;
delete  myChar; // release memory which was allocated with new 
Topic archived. No new replies allowed.