0

I really need to do something like this in my code: char str[var+1]; but i know you can only put a constant between []. So i'm just asking if there is any way of doing what i need.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
Anda
  • 670
  • 7
  • 7

2 Answers2

6

It is only possible to declare a variable of compile time constant size in C++.

However, dynamic arrays can have a dynamic size. Simplest way to create a dynamic array is to use std::vector, or in case of character string you can use std::string. Example:

 std::string str(var+1, '\0');
eerorika
  • 232,697
  • 12
  • 197
  • 326
1

Question originaly included the C and C++ tag, this answer is for C

in C, var can be non-constant for VLA suporting standards (c99 and optional support in c11)

The following is valid in C (see : https://godbolt.org/z/kUockA)

int var=3;
char str[var+1];

However VLA are not defined in the C++ standard (see: https://stackoverflow.com/a/1887178/105104 ) and not recommended to use in C either.

Because VLA are usually allocated on the stack and if the value of var is not controlled the allocation of str can fail, and recovery of such failure can be difficult. Additionally they could encourage the creation of highly unsafe code (if one would want to make pointer arithmetic on stack allocated variable).

There was an initiative to make the linux kernel code VLA-free (see : https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA ):

  • Using variable-length arrays can add some minor run-time overhead to the code due to needing to determine the size of the array at run-time.

  • VLAs within structures is not supported by the LLVM Clang compiler and thus an issue for those wanting to build the kernel outside of GCC, Clang only supports the C99-style VLAs.

  • Arguably most importantly is there can be security implications from VLAs around the kernel's stack usage.

Community
  • 1
  • 1
dvhh
  • 4,724
  • 27
  • 33