Using "new" in C++ vs array[123] or *array = malloc(123)

This is a discussion on Using "new" in C++ vs array[123] or *array = malloc(123) within the C Programming forums, part of the General Programming Boards category; Sorry if this is an easy question, but I don't know anything about C++ and have been dabbling with some ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    97

    Using "new" in C++ vs array[123] or *array = malloc(123)

    Sorry if this is an easy question, but I don't know anything about C++ and have been dabbling with some libraries written in C++.

    Is there any difference between these statements?

    Code:
    uint8_t mybuffer[100]; //C
    
    uint8_t *mybuffer = new uint8_t[100]; //C++

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Yes... one works in C the other does not.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    And of course the type of mybuffer would be different in each case; the second one will necessarily use extra storage (since you'll have the storage for the pointer plus the 100 uint8_t elements); it is your responsibility to clean up the memory in the second case with delete[], while the system will take care of the first one for you.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    Yes there is. Use the first one when possible.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 02-28-2008, 10:51 PM
  2. how can i pass by reference by "malloc 2d array"?
    By Mathsniper in forum C Programming
    Replies: 10
    Last Post: 05-22-2005, 02:23 PM
  3. Replies: 2
    Last Post: 07-22-2004, 02:25 AM
  4. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have "
    By L.O.K. in forum Windows Programming
    Replies: 5
    Last Post: 12-08-2002, 07:25 AM
  5. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 06:59 AM

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