简体   繁体   中英

What is the difference between following two snippets?

char *t=new char();

and

char *t=new char[102];

as my code was accepted by using the latter one?

//BISHOPS SPOJ
char *t=new char();

Allocates memory for a single character, and calls the default constructor.

char *t=new char[102];

Creates an array of 102 char s and calls the default constructor.

As the default constructor for POD types is nothing, the difference is the amount of memory allocated (single char vs array of char)

Actually both are pointers on char , but second is pointer to char array.

Which allows you to store 102 characters into the array.

char *t=new char[102];

  0   1   2   3       101
+---+---+---+---+ ... +---+
|   |   |   |         |   |
+---+---+---+---+ ... +---+
  ^
  |
  -----------------------------+---+
                               | * |
                               +---+
                                 t

It allows you to dereference these indexes 0-101.


While first one allows you to store only one character.

char *t=new char();
  0
+---+
|   |
+---+
  ^
  |
  -----------------------------+---+
                               | * |
                               +---+
                                 t

Where dereferencing other index than 0 would lead to access outside of bounds and undefined behavior.


Deleting

To delete an character char *t=new char();

delete t;

Where to delete an array char *t=new char[102]; you have to write empty brackes, to explicitly say its an array.

delete [] t;

Same with these codes

char *t = new char[10];  // Poitner to array of 10 characters

char *t = new char(10);  // Pointer to one character with value of 10

Memory initialialization

char *t = new char();      // default initialized (ie nothing happens)
char *t = new char(10);    // zero    initialized (ie set to 0)

Arrays :

char *t = new char[10];   // default initialized (ie nothing happens)
char *t = new char[10](); // zero    initialized (ie all elements set to 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM