Char Array Size Problem
Apr 27, 2014 at 9:47pm UTC
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:
char myChar[6];
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:
char myChar[6];
Yay! It works!!!
But when I do:
1 2
int val = 6;
char myChar[val];
It doesn't work.
Why is this and how can I fix it???
Thanks! -Luna
Apr 28, 2014 at 12:37am UTC
if you want to create the array at runtime then you need a dynamic array.
char *myChar = new char [val];
Apr 28, 2014 at 1:31pm UTC
1 2 3
#include <iostream>
using namespace std;
#define var 6
should work fine
Apr 28, 2014 at 2:05pm UTC
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <vector>
#include <string>
int main()
{
int var;
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[0] = myString[0] = myVec[0] = 'A' ; // put something in first element
std::cout << myChar[0] << std::endl;
std::cout << myString[0] << std::endl;
std::cout << myVec[0] << std::endl;
delete [] myChar; // release memory which was allocated with new []
return 0;
}
Topic archived. No new replies allowed.