Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't create an array of doubles

Tags:

arrays

c

double

I'm trying to create an array of doubles, and I know I can do it like this,

double a[200];

but why can't I create one like this?

int b = 200;

double a[b];

It does not work.

Can anyone help me?

UPDATE:

int count;
count = 0
while (fgets(line,1024,data_file) != NULL)
{
    count++;
}

double *x = (double *)malloc(count * sizeof (double));

double xcount = 1.0;

for (int i = 0; i < count; i++)
{
    x[i] = xcount/f;
    xcount = xcount + 1.0;
    printf("%lf\n", x[i]);
}
like image 518
SamuelNLP Avatar asked Nov 21 '25 12:11

SamuelNLP


2 Answers

C doesn't support dynamic array sizes. You'll have to dynamically allocate memory and use a pointer.

int b = 200;

double *a;
a = malloc(b * sizeof (double));

After this, you can access a as if it were an array.

like image 143
DoxyLover Avatar answered Nov 23 '25 00:11

DoxyLover


@DoxyLover is totally correct, in addition if what you want is to use a constant number as the size of array, you could use a marco like #define kMaxN 200 or const int kMaxN = 200 for C++.

If you want to alloc an array in function, you could use it like

int foo(int n) {
  int a[n];
}

or if you want to pass a multi-dimension array as a parameter you can use

int foo(int n, int arr[][n]) {
...
}
like image 41
fLOyd Avatar answered Nov 23 '25 00:11

fLOyd