English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I want to make an array for a complicated program

but basically these two line dont work

int v=10; // initialize int to 10
int array[v]; //declare array with 10 elements

By itself :
int array[10]; WORKS but I need to use it in a function, so why is the top not working thanks :)

2007-03-07 16:42:18 · 6 answers · asked by dragongml 3 in Computers & Internet Programming & Design

6 answers

where v is variable, its not allowed. its better to try as
#define v 10
or
const int v=10;
now its working,
bcoz array declaration requires a constant.
i think u understand

2007-03-07 16:56:14 · answer #1 · answered by sanjeeva 1 · 0 0

Whenever you declare an array the dimension specifications should always be a constant and not a variable. So when you do the above declaration it will result in compilation errors. In this case if u need the size of array to be dynamic , then you can implement arrays using a pointer. But pointer allocations and processing should be clear or else you would get junk values.

2007-03-08 01:34:58 · answer #2 · answered by JayCee 1 · 0 0

v is a varible that isn't set until run time, so the compiler cannot use as part of array declaration. You have to use "new" to dynamically allocate an array in C++

Or you can use #define v 10

2007-03-08 00:54:51 · answer #3 · answered by Al Bunn 3 · 0 0

If you want your array memory to be allocated at compile time, array size must be constant. Thus, you need:
const int n = 10;
int array[n];
For dynamic allocation, you can use variable:
int n = 10;
int *array = new int[n];
/* do not forget to free dynamically allocated memory after using your array: */
...
delete [] array;

2007-03-08 01:25:42 · answer #4 · answered by alakit013 5 · 1 0

start off with declaring another variable 'i' which defines the order of filling the array,or the block of array under consideration. next use 'for loop'

2007-03-08 00:48:29 · answer #5 · answered by ::Ð嬢Y¢LøÞs:: 3 · 0 1

you need to allocate memory dynamically do so
like
int *array;
array = new int[v]

2007-03-08 04:08:30 · answer #6 · answered by Anonymous · 0 0

fedest.com, questions and answers