Thread: Array Problem

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    215

    Array Problem

    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.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    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.

    Code:
    int * B = new int[r-p+1];
    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.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    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:
    Code:
    int x;
    cout<<"enter an array size: ";
    cin>>x;
    int myArr[x];
    Nor can you do what you are trying.

    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.
    Code:
    int x;
    cout<<"enter an array size: ";
    cin>>x;
    int* p = new int[x];
    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:
    delete[] p;
    Last edited by 7stud; 06-05-2005 at 11:11 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array problem
    By TomBoyRacer in forum C++ Programming
    Replies: 3
    Last Post: 04-08-2007, 11:35 AM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Replies: 6
    Last Post: 02-15-2005, 11:20 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Need desperate help with two dimensional array problem
    By webvigator2k in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2003, 02:28 PM