0

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;
}
  1. cout << ptr; prints helloworld (prints value); cout << ptr1 prints address not value. Why??
  2. Since cout << ptr; prints value, How to get address that new char[11] assigns to ptr.
  3. If ptr = "helloworld"; is allowed. why ptr1 = {12, 24}; is not allowed?
4

2 回答 2

6

您问题的核心是为什么 << 运算符在一种情况下输出字符串,而在另一种情况下输出地址。这是来自它的 c 语言遗产,其中没有“真正的”字符串类型。在 c/c++ 中,char* 和 char[] 被唯一地处理,通常假定为“字符串”。其他类型的数组被假定为该类型的数组。因此,当输出 char* 时,<< 假定您想要一个字符串输出,而使用 int[] 时,它输出数组的地址而不是它的内容。简单地说,char[] 和 char* 在许多输出函数中都被视为特殊情况。

我可以看到您对编译器处理您的源代码的方式也有一些困惑。考虑:

char* ptr = new char[11];
ptr = "helloworld";

此代码分配 11 个字符的内存并将 ptr 设置为该分配的地址。下一行创建一个常量“helloworld”,它被分配和初始化,并将 ptr 设置为该内存的地址。您有两个内存位置,一个有 11 个未初始化的字符,一个初始化为“helloworld\0”。

于 2013-10-27T15:54:55.920 回答
0

您的代码有一个主要问题,那就是内存泄漏。您分配内存并将其分配给ptr,然后重新分配它以使其指向其他地方。如果您希望内存包含字符串,则必须将其复制到分配的内存中。

并且该语言不允许使用“文字数组”,除非在声明中初始化数组。

于 2013-10-27T15:21:46.967 回答