There are some doubts related to given program below. Any discussion will be helpful to understand the internals.
#include <iostream>
using namespace std;
int main() {
// your code goes here
char* ptr = new char[11];
ptr = "helloworld";
cout << ptr;
int* ptr1 = new int[2];
//ptr1 = {12, 24};
cout << ptr1;
return 0;
}
- cout << ptr; prints helloworld (prints value); cout << ptr1 prints address not value. Why??
- Since cout << ptr; prints value, How to get address that new char[11] assigns to ptr.
- If ptr = "helloworld"; is allowed. why ptr1 = {12, 24}; is not allowed?
The heart of your question is why does the << operator output a string in one case but an address in another. This is from it's c language heritage where there wasn't a 'true' string type. In c/c++ char* and char[] are handled uniquely and generally assumed to be a 'string'. Arrays of other types are assumed to be arrays of that type. So when outputting a char* the << assumes you want a string output, while with int[], it outputs the address of the array rather than it's content. Simply, char[] and char* are treated as special cases in a lot of output functions.
I can see that you also have some confusion regarding the way the compilers processes your source. Consider:
char* ptr = new char[11];
ptr = "helloworld";
This code allocations 11 char's of memory and sets ptr to the address of that allocation. The next line creates a constant "helloworld" which is allocated and initialized and sets ptr to the address of that memory. You have two memory locations, one with 11 uninitialized chars and one initialized to "helloworld\0".
You have a major problem with your code, and that is a memory leak. You allocate memory and assign it to ptr
, but then you reassign it to make it point somewhere else. If you want the memory to contain a string you have to copy it into the allocated memory.
And "literal arrays" are not allowed by the language, except when initializing an array in a declaration.
来源:https://stackoverflow.com/questions/19619682/why-char-and-int-behaves-differently