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

关于C语言指针的疑问:为何str[0]与&str[0]地址不同?

指针数组地址疑问解答

问题描述

我目前就读于技术学校,已学习指针相关知识,但仍有部分内容存在困惑。我的疑问如下:已知str[0]与&str[0][0]指向同一地址,为何str[0]的地址(即&str[0])却与之不同?

代码示例

int main(void)
{
    char *str[] = {"Hello", "World"};

    printf("adress of 'H' : %p\n", str[0]);
    printf("adress of Hello strings : %p\n", &str[0]);
    printf("point to the string Hello and we point to the adress of 'H' (str[0][0]) : %c\n", str[0][0]);
    printf("adress of adress what str[0][0] points : %p\n", &str[0][0]);
    printf("\n");
    printf("adress of 'W' : %p\n", str[1]);
    printf("adress of World strings : %p\n", &str[1]);
    printf("point to the string World and we point to the adress of 'W' (str[1][0]) : %c\n", str[1][0]);
    printf("adress of what str[1][0] points : %p\n", &str[1][0]);
}

运行输出

adress of 'H' : 0x56xsxxxxxxxx
adress of Hello strings : 0x7ffcxxxxxxx
point to the string Hello and we point to the adress of 'H' (str[0][0]) : H
adress of adress what str[0][0] points : 0x56xsxxxxxxxx

adress of 'W' : 0x56xsxxxxxxxd
adress of World strings : 0x7ffcxxxxxxd
point to the string World and we point to the adress of 'W' (str[1][0]) : W
adress of what str[1][0] points : 0x56xsxxxxxxxd

解答

核心逻辑:变量本身的存储地址和它指向的地址是两回事

你定义的char *str[] = {"Hello", "World"}是一个指针数组:数组里的每个元素str[0]、str[1]都是独立的char*指针变量,这些变量本身需要占用栈内存;而它们指向的字符串"Hello"、"World"则存储在程序的常量数据区,两个区域完全分离。

逐个解析地址含义

  1. str[0] 和 &str[0][0]

    • str[0]是指针数组的第一个元素,它的值是字符串"Hello"首字符'H'的地址(也就是常量区里"Hello"的起始地址)。
    • str[0][0]等价于*(str[0]),即str[0]指向地址里的内容(也就是'H');&str[0][0]是取这个字符的地址,自然和str[0]存储的地址完全一致,所以输出相同。
  2. &str[0]

    • &str[0]取的是str[0]这个指针变量本身的存储地址,也就是该指针在栈上的位置。
    • 栈内存(存储指针变量)和常量数据区(存储字符串)是完全不同的内存区域,所以这个地址和str[0]指向的地址必然不同。

对应你的输出验证

  • 以Hello相关输出为例:
    • 0x56xsxxxxxxxx是常量区中'H'的地址,对应str[0]和&str[0][0];
    • 0x7ffcxxxxxxx是栈上str[0]这个指针变量的地址,对应&str[0]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:56:05