Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between new char[10] and new char(10)

Tags:

c++

In C++, what's the difference between

char *a = new char[10]; 

and

char *a = new char(10); 

Thanks!

like image 231
geschema Avatar asked Oct 10 '10 20:10

geschema


People also ask

What is new char in C++?

You can create an array with zero bounds with the new operator. For example: char * c = new char[0]; In this case, a pointer to a unique object is returned. An object created with operator new() or operator new[]() exists until the operator delete() or operator delete[]() is called to deallocate the object's memory.

What does char * s mean in C?

Difference between char s[] and char *s in CThe s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4. The first one will be 20 as it is showing that there are 20 bytes of data.

What is the difference between char * C and char * C?

The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test" , while the pointer simply refers to the contents of the string (which in this case is immutable).

Is 10 a char in C?

Character 10 can be represented by '\n' in C code, as well as '\012' , '\x0a' , and '\u000a' Character 13 (carriage return) can be represented by '\r' , '\015' , '\x0d' , and '\u000d' . Worth noting perhaps that in C it is represented by the escape sequence \n .


2 Answers

The first allocates an array of 10 char's. The second allocates one char initialized to 10.

Or:

The first should be replaced with std::vector<char>, the second should be placed into a smart pointer.

like image 59
GManNickG Avatar answered Sep 21 '22 02:09

GManNickG


new char[10]; 

dynamically allocates a char[10] (array of char, length 10), with indeterminate values, while

new char(10); 

again, dynamically allocates a single char, with an integer value of 10.

like image 31
eq- Avatar answered Sep 20 '22 02:09

eq-