1

I've done quite a bit of research on how to set an arrays size using a variable of datatype int, but haven't been able to find anything of use.

So here is an example of what I've tried in which gives me an error saying "expression must have a const value"

char * charptr = "test";
int sze = strlen(charptr);
char str[sze];

Sorry if this question is idiotic, I'm still quite new to c++

Any help will be appreciated though!

C0d1ng
  • 441
  • 6
  • 17
  • 2
    An excellent choice would be to use `std.:string` instead of a `char` array. – Bo Persson Jul 05 '16 at 08:42
  • 2
    If you are new to C++, you should not use pointers. Pointers are a low-level expert tool, mainly for optimizing implementations and for low-level operations, and they should not be necessary to just get something working. – Kerrek SB Jul 05 '16 at 08:43
  • You can't do that in standard C++, but some C++ compilers have extensions that let you do it. Given that we have the C++ standard containers, it's not a very interesting feature. – molbdnilo Jul 05 '16 at 08:44
  • @KerrekSB I am not writing my c++ 'program' on windows or anything like that, string.h is unavailable to me. – C0d1ng Jul 05 '16 at 08:49
  • Possible duplicate of [Can I use a C Variable Length Array in C++03 and C++11?](http://stackoverflow.com/questions/31645309/can-i-use-a-c-variable-length-array-in-c03-and-c11) – Julien Lopez Jul 05 '16 at 08:50
  • @C0d1ng: What has `string.h` to do with anything? That header is deprecated in C++ anyway. – Kerrek SB Jul 05 '16 at 10:21
  • @KerrekSB lol, i am unable to use the string struct (string.h) unless i were to re-create it. So in my case i need to use char* or char[] – C0d1ng Jul 05 '16 at 10:30
  • @C0d1ng: You're thinking of a completely different header, ``. – Kerrek SB Jul 05 '16 at 10:33
  • @KerrekSB ok? I meant the same thing, i never use it nor need it so easy to mix up – C0d1ng Jul 05 '16 at 10:39

2 Answers2

2

You have to use dynamic allocation.

int size = 1337;
char *str = new char[size];

By doing this, the program will allocate memory on the heap during runtime.

You cannot do char str[size] because size is not known at compile time and then the compiler does not know how much space it has to allocate on the stack.

Of course remember to do delete [] str after its usage.

Mattia F.
  • 1,720
  • 11
  • 21
2

sze is not known at compile-time; C++ does not support variable length arrays so char str[sze]; is not valid C++.

One workaround would be to use char* str = new char[sze]; but this can cause you problems since you must balance this with a subsequent delete[] str; else you'll leak memory.

It's far better to use the built-in string class std::string if you can.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483