Why char* and int* behaves differently [closed]

血红的双手。 提交于 2019-12-02 13:08:34

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!