# Thread: Convert double to int for array size

1. ## Convert double to int for array size

Hi,

I want to declare an array size based on a double calculation. Rounding it up or down doesn't really matter. As the array size needs to be an integer, is there any way I can convert the double result to an integer?

2. i = (int)d;

Otherwise known as "look it up".

3. Rounding it up or down probably does matter. Depending on round-off error and all that good stuff. If the result was very close to an integer (meant to be an integer but could be +/- some tiny fraction) you have to find the closest integer. Usually something like
Code:
`i = (int)(d + 0.5);`

4. I need to use the int value to declare the array size. However when I try the suggested responses it does not work.

It says "integral constant expression expected"

double z = x/y;
int a = (int) z;

int array1 = [a];

5. Code:
`int array1 = [a];`
That is not how you declare an array. You need to pick up a book, or read through some tutorials online.

At any rate, try this:
Code:
`int array1[a];`

6. Originally Posted by bithub
Code:
`int array1 = [a];`
That is not how you declare an array. You need to pick up a book, or read through some tutorials online.

At any rate, try this:
Code:
`int array1[a];`
My apologies, that was a typo. However the code with the correct syntax is not working.

double z = x/y;
int a = (int) z;

int array1[a];

I'm still getting "integral constant expression expected".

7. Originally Posted by millsy5
I'm still getting "integral constant expression expected".
That is because unless you are compiling with respect to C99, this is wrong:
Code:
```int a = (int) z;

int array1[a];```
You are trying to create a variable length array, and that is not allowed in standard C prior to the 1999 edition of the C standard.

8. check out malloc:

#include <stdlib.h>

int *array1 = NULL;
array1 = malloc(a * sizeof(int));

memory allocated by malloc should be later freed and the pointer set to null:

free(array1);
array1 = NULL;

9. Originally Posted by laserlight
That is because unless you are compiling with respect to C99, this is wrong:
Code:
```int a = (int) z;

int array1[a];```
You are trying to create a variable length array, and that is not allowed in standard C prior to the 1999 edition of the C standard.
Thanks. How do I check which compiler I am using?

10. Originally Posted by millsy5
Thanks. How do I check which compiler I am using?
By ... how you run the compiler? If you type "gcc" you're using gcc, et cetera. If you push a button, then you should know what program you downloaded that has a button you can push, and that program will tell you what the compiler is.

Popular pages Recent additions