0

I recently saw a code and it declared an array using function parameter as array's size. I don't know how, but this code compiles and works properly (using gdb online). Do you know what compiles do in this case?

Code used:


void foo(int size) 
{
    size++;
    char arr[size];
    
    for (int i = 0; i < size; i++) {
        arr[i] = i;
        printf("arr[%d] = %d\r\n", i, arr[i]);
    }
    
}

int main()
{
    printf("Hello World\r\n");
    
    foo(10);

    return 0;
}

The output of this code is:

Hello World
arr[0] = 0
arr[1] = 1
arr[2] = 2
arr[3] = 3
arr[4] = 4
arr[5] = 5
arr[6] = 6
arr[7] = 7
arr[8] = 8
arr[9] = 9
arr[10] = 10


...Program finished with exit code 0
Press ENTER to exit console.
  • 1
    Why have you added the c++ tag? That's a variable length array, BTW. – Bob__ Nov 30 '21 at 16:20
  • I understand that C does not have a variable array, c++ has a vector class... I used c++ tag because some c++ developers have good knowledge about c. – Felipe Moura Oliveira Nov 30 '21 at 16:33
  • 2
    C *does* have [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) (but compilers might not support them since C11). C++ does not have variable length arrays, and `std::vector` uses the equivalent of `malloc` under the hood – Artyer Nov 30 '21 at 16:41
  • 1
    @FelipeMouraOliveira I see. Please note that's not how tags are supposed to used. Besides, a C tag would be enough to attract C developers, which supposedly would have a better knowledge of that language ;) – Bob__ Nov 30 '21 at 17:34

0 Answers0