You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中获取char数组内存地址时输出多个'Z'的原因

问题:char数组内存地址输出为何显示多个'Z'?

我编写了一段C++代码,创建了两个数组:一个存储0到20的整数,另一个存储20个字符'Z'。代码设置数组长度后,分别为int数组和char数组赋值,随后打印两个数组的元素及其内存地址。运行后,int数组正常输出元素对应的内存地址,但char数组却输出多个连续的'Z'而非内存地址,具体代码及运行结果如下:

#include <iostream>
using namespace std;

int main()
{
        
    //Use & to find the address locatoin in memory
    
    int arrayLength = 20;
    
    int integerArray[arrayLength];
    
    for (int i = 0; i <= arrayLength; i++){
    
        integerArray[i] = i;
    
    }
    
    cout << "-------------------------" << endl;
    for (int i = 0; i <= arrayLength; i++){
    
        cout << integerArray[i] << " is stored at: " << &integerArray[i] << endl;

    }
    
    char charArray[arrayLength];
    
    for (int i = 0; i <= arrayLength; i++){
    
        charArray[i] = 'Z';
    
    }
    
    cout << "-------------------------" << endl;
    for (int i = 0; i <= arrayLength; i++){
    
        cout << charArray[i] << " is stored at: " << &charArray[i] << endl;

    }
    
    return 0;
}

运行结果:

-------------------------
0 is stored at: 0x7ffd40dc8f40
1 is stored at: 0x7ffd40dc8f44
2 is stored at: 0x7ffd40dc8f48
...
20 is stored at: 0x7ffd40dc8f90
-------------------------
Z is stored at: ZZZZZZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZZZZZZ
...
Z is stored at: Z

原因分析

这是C++标准库的cout对char*类型的特殊处理导致的:

  • 当输出&charArray[i]时,得到的是一个char*指针,cout会默认把它当作C风格字符串处理——从该地址开始连续输出字符,直到遇到'\0'(空字符)才停止。
  • 你的代码存在两个问题:一是数组越界赋值,charArray长度为20,但循环用了i <= arrayLength,会给超出数组范围的charArray[20]赋值;二是整个数组内全是'Z',没有'\0'终止符,甚至越界操作覆盖了内存中原本可能存在的终止符,导致cout一直输出'Z',直到碰到内存中随机的'\0'才停下。
  • 而int*类型指针(比如&integerArray[i])没有这种特殊逻辑,cout会直接输出其内存地址值。

解决方法

  1. 强制转换指针类型:把char*指针转为const void*,让cout输出内存地址而非字符串:
    cout << charArray[i] << " is stored at: " << static_cast<const void*>(&charArray[i]) << endl;
    
  2. 修复数组越界:将循环条件改为i < arrayLength,避免访问超出数组范围的内存:
    // 赋值循环
    for (int i = 0; i < arrayLength; i++){
        charArray[i] = 'Z';
    }
    // 打印循环
    for (int i = 0; i < arrayLength; i++){
        cout << charArray[i] << " is stored at: " << static_cast<const void*>(&charArray[i]) << endl;
    }
    

内容的提问来源于stack exchange,提问作者SilverKnightOfTheUnion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 14:22:06