3

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]);
}
SamuelNLP
  • 4,038
  • 9
  • 59
  • 102
  • 3
    Because arrays have a constant size. Well, C has some new-ish feature called VLAs which allows this, but your compiler must not support it. – Pubby Mar 04 '13 at 02:17

2 Answers2

3

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
  • 3,366
  • 1
  • 15
  • 19
  • In that case it would be something like, `a = (double *)malloc(b * sizeof (double));` instead, right? – SamuelNLP Mar 04 '13 at 02:26
  • 1
    There is no need for casting `void *` (as the return value of `malloc` is) – MByD Mar 04 '13 at 02:27
  • `invalid conversion from 'void*' to 'double*' [-fpermissive]` – SamuelNLP Mar 04 '13 at 02:29
  • 1
    C99 supports variable length arrays.http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html http://stackoverflow.com/a/6656785/1944441 –  Mar 04 '13 at 02:31
  • 1
    its not a dynamic array , its just a variable sized array , dynamic is when you perform it during runtime – Barath Ravikumar Mar 04 '13 at 02:32
  • @SamuelNLP: I'm guessing you're compiling with g++ to get that error. It's fine in C, C++ requires a cast. – teppic Mar 04 '13 at 02:35
  • yes, I'm compiling with g++. but then how can I say `a[1] = 0;`? – SamuelNLP Mar 04 '13 at 02:38
  • @SamuelNLP: if you compile with gcc, you can just use the code above as you want to without any of this. If you do need to use C++, you can still use array subscripting like a[1] on a pointer. – teppic Mar 04 '13 at 02:40
  • Ok, but when I try to print x in a for, `print("%lf\n", x[i]);` it is giving me SIGABRT error. – SamuelNLP Mar 04 '13 at 02:45
3

@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]) {
...
}
fLOyd
  • 385
  • 1
  • 2
  • 9
  • I have a text file and my b is the result of counting the lines, so it can't be constant. after counting the lines i'm creating an array to reread the lines but this time adding the values in it to the array. – SamuelNLP Mar 04 '13 at 02:33