1

Is it possible to declare a variable when initializing an array?

For example:

#include <stdio.h>

main()
{
    int x;
    int arr[x];
    
    scanf("%i", &x);
}

Or perhaps something similar?

Any help would be appreciated.

4
  • x needs to have a value before it's used to size arr. Commented Apr 16, 2021 at 19:43
  • Programs in C are sequential. At a time of arr definition it does not know about the future value of x. Commented Apr 16, 2021 at 19:44
  • Put the scanf between the two variables. Commented Apr 16, 2021 at 19:48
  • ah ok. Thank you very much Commented Apr 16, 2021 at 19:50

1 Answer 1

1

In general you may write

int x;
scanf("%i", &x);
int arr[x];

In this case the array arr will be a variable size array. The value of x shall be greater than 0.

Otherwise in this case

int x;
int arr[x];

the variable x is uninitialized (because it is a variable with automatic storage duration) and as a result the array declaration invokes undefined behavior.

Sign up to request clarification or add additional context in comments.

1 Comment

OP should note that, as written, this is an exploitable stack overflow bug.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.