Im Trying to initialize this array and when I do this:
code:
void merge(int A[], int p, int q, int r)
{
int B[r-p+1];
/code
It doesnt work, i get an error because the compiler doesnt know what r and p are.
Printable View
Im Trying to initialize this array and when I do this:
code:
void merge(int A[], int p, int q, int r)
{
int B[r-p+1];
/code
It doesnt work, i get an error because the compiler doesnt know what r and p are.
I think what you are trying to do would only work with a C99 compliant compiler. You need to allocate memory for the array dynamically.
You should ensure r-p+1 is positive and you will also need to remember to delete the memory once you are done with the array.Code:int * B = new int[r-p+1];
An array's dimension has to be a constant integer. Those are the rules. So, you can't have variables listed for an array's dimension, e.g. you can't do this:
Nor can you do what you are trying.Code:int x;
cout<<"enter an array size: ";
cin>>x;
int myArr[x];
If you need to use a variable for an array's dimension, then you have to know what pointers are and you have to know how to dynamically allocate memory, e.g.
You also have to delete any memory that you dynamically allocate with new after you are done with it. In this case, that would take the form:Code:int x;
cout<<"enter an array size: ";
cin>>x;
int* p = new int[x];
Code:delete[] p;