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

数组与指针的关系:为何C程序未打印a[i]却输出地址?

数组与指针的核心关系 + 你的程序问题解析

Hey there! Let's walk through this—this is one of the most common "wait, why is this happening?" moments when learning C arrays and pointers, so you're definitely not alone here.

First, let's nail down the key relationship between arrays and pointers in C:

  • An array name (like a in your code) acts as a constant pointer to the first element of the array. So if you have int a[5];, a is equivalent to &a[0]—but you can't modify it (you can't do a++ like you would with a regular pointer, since it's fixed to the start of the array).
  • The array subscript syntax a[i] is actually just sugar for *(a + i) under the hood. C takes the pointer to the first element, adds i times the size of the array's data type, then dereferences that address to get the value stored there.
  • Fun fact: You can even use subscript syntax with regular pointers! If you have int *ptr = a;, ptr[i] works exactly like a[i]—the two are interchangeable here (the only difference is that ptr is a modifiable pointer, while a is constant).

Now, why is your program printing addresses instead of the a[i] values? The most common culprits are:

  1. Wrong printf format specifier
    If you used %p (the specifier for printing memory addresses) instead of the specifier matching your array's type, C will treat the value of a[i] as an address and print it. For example:

    int a[] = {10, 20, 30};
    printf("%p", a[1]); // Oops! This prints the "address" represented by the value 20, not 20 itself
    

    Fix this by using the correct specifier: %d for integers, %f for floats, etc. So the correct line would be printf("%d", a[1]);.

  2. Printing the pointer itself instead of dereferencing it
    If you accidentally wrote a + i instead of a[i] (or *(a + i)), you're printing the memory address of the i-th element, not the value stored there. For example:

    int a[] = {10, 20, 30};
    printf("%d", a + 1); // Prints the address of a[1], not 20
    

    To fix this, either use the subscript syntax a[i] or explicitly dereference the pointer with *(a + i).

One quick extra note: When you pass an array to a function, the array name "decays" into a regular modifiable pointer. That means inside the function, you can do things like ptr++ to move through the array, even though you can't do that with the original array name in its defining scope.

Hope that clears up the confusion! If you share your actual code snippet, we can zero in on the exact line causing the issue—but these are the two most common reasons for this behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:42:19