[英]Understanding memory allocation behaviour for arrays using malloc
I have this simple code:我有这个简单的代码:
#include<stdio.h>
#include<stdlib.h>
int main(){
int (*array)[2] = malloc(sizeof(int)*2);
printf("%p\n",array[0]); //0x13c606700
printf("%p\n",array[0]+1); //0x13c606704
printf("%p", array[1]); //0x13c606708
}
I'm using malloc to allocate memory for an integer array of 2 elements.我正在使用 malloc 为 2 个元素的整数数组分配内存。 This returns a pointer for this said array.
这将返回该数组的指针。 However, I don't understand why
array[0]+1
and array[1]
are yielding different addresses.但是,我不明白为什么
array[0]+1
和array[1]
会产生不同的地址。 array[0]+1
prints the address at array[0]
+ 4 which is expected since an integer is of size 4 bytes. array[0]+1
打印array[0]
+ 4 处的地址,这是预期的,因为整数的大小为 4 个字节。 But this is not the same for array[1]
.但这与
array[1]
。 Why is this happening?为什么会这样? Wouldn't intuition suggest that using malloc on a fixed-size array would enable the programmer to refer to the memory allocated using array notation (ie array[i])?
直觉是不是暗示在固定大小的数组上使用 malloc 会使程序员能够引用使用数组符号(即数组 [i])分配的内存?
array[0]
is an int[2]
. array[0]
是一个int[2]
。 When passed to the function it decays into a pointer to the first element, an int
, which is 4 bytes on your system.当传递给函数时,它会衰减为指向第一个元素的指针,一个
int
,它在您的系统上占 4 个字节。
array[0] + 1
adds the sizeof(int)
to the pointer. array[0] + 1
将sizeof(int)
到指针。
array[1]
is the next int[2]
(out of bounds). array[1]
是下一个int[2]
(越界)。 That's the sizeof(int)
times two.这是
sizeof(int)
乘以 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.