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?
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?
i = (int)d;
Otherwise known as "look it up".
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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);
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];
That is not how you declare an array. You need to pick up a book, or read through some tutorials online.Code:int array1 = [a];
At any rate, try this:Code:int array1[a];
bit∙hub [bit-huhb] n. A source and destination for information.
That is because unless you are compiling with respect to C99, this is wrong:Originally Posted by millsy5
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.Code:int a = (int) z; int array1[a];
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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;