Dynamic Memory Allocation

This is a discussion on Dynamic Memory Allocation within the C++ Programming forums, part of the General Programming Boards category; I'm attempting to do some basic dynamic memory allocation and I've run into a problem I cannot seem to get ...

  1. #1
    fr0ggs
    Guest

    Question Dynamic Memory Allocation

    I'm attempting to do some basic dynamic memory allocation and I've run into a problem I cannot seem to get around. First, if I try the following bit of code:

    int x,y;
    cin >> x;
    cin >> y;
    int arr [x][y];

    I get the following compiler error:

    "Constant expression required in function foo()"

    In trying to skirt the above issue, I tried to code it this way:

    int x,y;
    cin >> x;
    cin >> y;
    int ** x1;
    x1 = new int [x][y];

    I get the same error as above plus:

    "Cannot convert int(*)[1] to int **."

    Am I coding this incorrectly?

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You can do something like this -

    int x,y;
    cin >> x;
    cin >> y;
    int ** x1;
    x1 = new int*[x];
    for(int i=0;i<y;i++)
    x1[i]=new int;

    You'll have to use a similar procedure when freeing the memory(only in reverse).
    zen

  3. #3
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Sorry, ignore the above . It should be -

    int x,y;
    cin >> x;
    cin >> y;
    int ** x1;
    x1 = new int*[x];
    for(int i=0;i<x;i++)
    x1[i]=new int[y];
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Replies: 16
    Last Post: 01-01-2008, 03:07 PM
  3. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  4. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21