CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2003
    Posts
    815

    Difference between new () and []

    Hi,

    Is there a difference between those 2 statements:

    str1 = new char[50];
    and
    str2 = new char(50);

    both str1 and str2 were defined like this:
    char* str1=null;
    char* str2= null;

    Thanks
    Avi

  2. #2
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Difference between new () and []

    Yes. The first one allocates 50 characters (50 times sizeof(char)) and the second statement allocates just one char initialized by a value 50.

  3. #3
    Join Date
    Apr 2007
    Posts
    14

    Re: Difference between new () and []

    The () notation calls a 'constructor' - which in the case of a primitive such as a char will just initialize it to that value. The [n] notation creates a contiguous block of memory with space for n objects of that type.
    Remember when you delete something you allocated with new[n] use delete[].

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured