0

I want to create an array of chars (char path[size] = "") while getting "size" from user.

When I try something like this:

int size = getSizeFromUser();

char path[size] = "";

I get a warning says "expression must have a constant value".

How can I do it right?

Thanks a lot!

Vipasana
  • 503
  • 1
  • 4
  • 13
  • 2
    Possible duplicate of [c++ array - expression must have a constant value](https://stackoverflow.com/questions/9219712/c-array-expression-must-have-a-constant-value) – Erlan Oct 25 '17 at 05:37
  • 1
    [Variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) are not part of C++, though some compilers have it as an extension. Your compiler doesn't seem to have that extension, and it should not be used for portable code. If you want an "array" whose size can be set at runtime then use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) for general data, or [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) for strings. – Some programmer dude Oct 25 '17 at 05:37
  • 1
    If you go for pointers (which I *really* don't recommend), then remember that `char` strings are really called ***null-terminated** character strings*. That *null-terminator* is important (and it's not the same as a null pointer). It means that a string of X characters needs space for X + 1 characters to include the terminator. – Some programmer dude Oct 25 '17 at 05:40

4 Answers4

2

In order to create a table with the users size you have to allocate your memory on the heap

int size = 4;
char *path = new char[size];

after using your array you have to manually delete it from the heap delete path;

inxoy
  • 3,484
  • 2
  • 13
  • 21
2

How can I do it right?

Variable length arrays aren't standard c++. The correct way to do it is to use a std::vector or a std::string instead of a raw array:

int size = getSizeFromUser();

std::string path(size,'\0');
user0042
  • 7,917
  • 3
  • 24
  • 39
1

If you declare char path[size]; then size has to be known at compile time. You read it at runtime so you need to use dynamic memory allocation, like char* path = new char[size]; and when you are finished call delete []path;.

If you want this to be a string with size visible characters, please consider that C-strings are null-terminated, meaning that you would have to reserve one extra char at the end of the array and set it to 0.

A better solution for a C++ program would probably be to use a std::string instead of a char*.

gonutz
  • 5,087
  • 3
  • 22
  • 40
1

When creating an array, its size must be constant.

If you want a dynamically sized array, you will have to allocate memory for it and you'll also need to free it when you're done with it.

To simply all these its always nice to use std::string

P0W
  • 46,614
  • 9
  • 72
  • 119