AskingQnsPro
AskingQnsPro

Reputation: 19

How to create a pre defined variable array in C

I am trying to create an array according to the size that the user inputs but it does not seem to be working for c programming. The following are my codes:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int x, y;
    scanf("%d", &x);
    scanf("%d", &y);

    double arr[x][y];
}

The compiler keeps returning an error of" Error: Expression must have a constant value. at the line double ... could anyone help point out the error?

Upvotes: 1

Views: 2209

Answers (5)

user529758
user529758

Reputation:

You have two choices:

  • Either use a decent C compiler that supports C99 (or later) and variable-length arrays (I'd go with this approach, personally);

  • or if that is not possible, or the resulting array would be too large to fit in a block-scope variable (causing, for example, a stack overflow), you can use malloc(); however, you won't be able to create a true two-dimensional array using that approach, only a pointer-to-pointer, which may or may not be what you are looking for.

Upvotes: 4

abkds
abkds

Reputation: 1794

You need to allocate the memory in run-time . The compiler doesn't allow the declaration of arrays becuase it does not know the size of the array before hand . You need to use malloc() to allocate memory

Upvotes: 0

kfsone
kfsone

Reputation: 24269

Older C standards don't provide support for arrays that do not have compile-time sizes:

int array[42];
char text[] = "Hello World";
int numbers = { 1, 2, 3, 4 };

(in the case of the latter two examples, the size is derived from the data)

You either need a newer compiler, to specify the -std=c99 if you are using GCC, or you need to allocate memory for the array yourself.

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122503

The code can work in C99 mode or when the compiler supports VLA(variable length arrays) as an extension (e.g, GCC supports VLA as GNU extesnion).

In C89, you have to use pointers with dynamic memory to simulate.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124800

You're using a C89 (Visual Studio? Though that would give you an error on the declaration of arr next) or a C++ compiler. VLA's (Variable Length Arrays) are a C99 feature.

Upvotes: 1

Related Questions