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]);
}
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.
@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]) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With