为什么char *和int *的行为不同 [英] Why char* and int* behaves differently

查看:454
本文介绍了为什么char *和int *的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下给定的程序存在一些疑问。任何讨论都有助于理解内部。

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;打印helloworld(打印价值); cout<< ptr1打印地址而不是值。为什么??

  2. 因为cout<< PTR;打印值,如何获取新char [11]分配给ptr的地址。

  3. 如果ptr =helloworld;被允许。为什么ptr1 = {12,24};是不允许的?


推荐答案

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

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";

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

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".

这篇关于为什么char *和int *的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆