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

指针数组与地址疑问:为何存储的地址和预期不一致?

指针数组地址打印差异问题

我正在学习指针数组相关内容,编写了一段测试代码,但代码第14行和第15行打印的结果并不相同,而它们本应输出student1[0]的地址。array_ptr中存储的值应该是student1的地址,但实际并非如此,希望有人能帮忙解释原因。

测试代码如下:

#include <stdio.h>
#include <string.h>

int main()
{
    char *array_ptr[5] = {0};

    char student1[] = {"Peter"};

    printf("%p\n", array_ptr[0]);

    array_ptr[0] = student1;

    printf("Address stored in Pointer: %p\n", array_ptr);
    printf("Address Student: %p\n", &student1);

    printf("Value Pointer: %s\n", *array_ptr);
    printf("Value Student1: %s\n", student1);

    return 0;
}

原因分析

  • 你搞错了打印对象:第14行的array_ptr是指针数组自身的首地址,不是数组第一个元素里存储的内容。数组名在表达式中会退化为指向数组第一个元素的指针,这里就是&array_ptr[0],也就是整个指针数组的起始地址,和你要打印的student1地址完全是两回事。
  • 要打印array_ptr中存储的student1地址,应该用array_ptr[0]或者*array_ptr——这两个才是指针数组第一个元素里存的值,也就是你之前赋值的student1的地址。
  • 补充说明:student1作为字符数组名,在表达式中会退化为指向首元素'P'的指针,所以student1、&student1[0]的值和&student1(整个数组的地址)的数值是相同的,只是类型不同。把第14行改成printf("Address stored in Pointer: %p\n", array_ptr[0]);,打印结果就会和第15行一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:42:26