Thread: allocating array of pointers

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    630

    allocating array of pointers

    Please help me something, im being confused about that:

    a code in c:

    Code:
    char **array = (char**)malloc(sizeof(char*) * number);
    what would be the proper way to do this in c++?

    Code:
    char **array = new char*[number];
    or
    char **array = new char*[sizeof(char *) * number];
    where the "number" is number of pointer.

    Thanks a lot for help.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > char **array = (char**)malloc(sizeof(char*) * number);
    Don't cast malloc in C - see the FAQ

    char **array = new char*[number];
    This one is correct.
    One advantage of new is that it always knows the type of thing it allocates, so the sizeof() is implicit in every call. All you have to care about is how many you want.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Allocating a 2D Array Differently
    By pianorain in forum C++ Programming
    Replies: 13
    Last Post: 12-15-2005, 02:01 AM
  2. array of pointers to struct array
    By eth0 in forum C++ Programming
    Replies: 1
    Last Post: 01-08-2004, 06:43 PM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  4. array of pointers to structs
    By stumon in forum C Programming
    Replies: 7
    Last Post: 03-24-2003, 07:13 AM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM