C++ Char Array No Set Value

Hello :D

I am making a console app in Visual Studio 2010 C++ and I was wandering if it is possible to make a char array that does not have a set value.

char test [any value];

Thanks for any help offered,

Muhasaresa
What you're describing is a variable length array. They are not allowed in C++, but C99 supports them.

In C++, you could use dynamic memory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int x = 0;
cin >> x;

if (x <= 0) return;

//using new (safe for objects)
char* test = new char[x];
test[0] = 'a';
test[x - 1] = 'b';
...
delete [] test;

//using malloc (not safe for objects)
char* test = (char*) malloc( x * sizeof(char) ); //malloc expects number of bytes
test[0] = 'a';
test[x - 1] = 'b';
...
free( test );

///using calloc (like malloc but zeroes the memory for you)
char* test = (char*) calloc(1, x * sizeof(char) );
test[0] = 'a';
test[x - 1] = 'b';
...
free ( test );


or you could use an object from STL such as a vector or list

1
2
3
4
5
6
7
#include <vector>

std::vector<char> test(x, 0); //initialize to have x values, each being zero (null)
test[0] = 'a';
test[x - 1] = 'b';

//no need to clean up 

Thanks :D
Topic archived. No new replies allowed.