In C++, what's the difference between
char *a = new char[10];
and
char *a = new char(10);
Thanks!
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.
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.
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).
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With