例如,假设您有一个数组 a 和一个指针 p。事情是这样的。
void main() {
int a[10];
int *p;
for(i = 0;i <=10;i++)
a[i] = (i + 1) * 2;
p = &a[0];
printf("%d",a[4]);
printf("%d",p[4]);
}
它们如何相等?
最佳答案
为什么数组的第一个元素等于数组?。假设您有一个整数数组,如 int arr[5];
然后根据你的问题标题
- 数组的第一个元素 将是
arr[0]
这是arr[0]
的值和 - array 表示
arr
和arr
names 表示数组的基址。所以arr
和arr[0]
不一样。arr
是基址 &arr[0]
是值(value)。
对于您的特定情况,整数数组 a
如下所示,数组的所有元素都存储在连续的内存位置。假设数组基址为0x100
(一些内存位置)
a[0] a[1] a[2] a[3] ........................................ a[9]
------------------------------------------------------------------------
| 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 |
------------------------------------------------------------------------
0x100 0x104 0x108 .. ..
a
LSB MSB
所以在这里a
表示 0x100
, 假设基地址为 a
是0x100
.现在当你这样做的时候
p = &a[0]; /* here you are setting p to point to one of the places in the array a and that is a[0] */
在这里p
指向 first
a
的元素即0x100
如下
a[0] a[1] a[2] a[3] ........................................ a[9]
------------------------------------------------------------------------
| 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 |
------------------------------------------------------------------------
0x100 0x104 0x108 0x112 0x116.. ..
a
|
p
现在当你打印 a[4]
它打印 10
正如预期的那样非常简单 & 它像下面这样扩展
a[4] = *(a + 4) /* here you can say that array name a is converted to a pointer to its first element */
= *(0x100 + 4*4 ) /* multiplied by 4 ? bcz a is int array & each element size is 4 byte */
= *(0x116) /* value at 0x116 memory location */
= 10
当你打印 p[4]
它展开如下
p[4] = *(p + 4)
= *(0x100 + 4*4) /*multiplied by 4 because int pointer increments by 4 bytes*/
= *(0x116) ? /* it prints value at 0x116 location which 10 */
= 10
同样在为 loop
中的数组元素赋值时,您正在尝试访问 a[10]
超出边界并导致未定义的行为。在下面的代码块条件部分应该是 i<10
而不是 i<=10
正如你声明的那样 a[10]
数组索引从 zero
开始.
for(i = 0;i <=10;i++) { /* make it i<10 */
a[i] = (i + 1) * 2;
}
最后void main() { /* code */ }
是不好的做法,它不符合 C 标准规范。使用 int main(void) { }
而不是 C 标准中指定的 n1256
草稿。
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.
关于c - 为什么数组的第一个元素等于数组?C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50655524/