开发者

Address of array vs. address of array[0] - C language

My question is why does the address of an array differ from the address of its first position?

I'm trying to write my own malloc, but to start out I'm just allocating a chunk of memory and playing around with the addresses. My code looks roughly like this:

#define BUFF_SIZE 1024
static char *mallocbuff;

int main(){
     mallocbuff = malloc(BUFF_SIZE);
开发者_高级运维     printf("The address of mallocbuff is %d\n", &mallocbuff);
     printf("The address of mallocbuff[0] is %d\n", &mallocbuff[0]);
}

&mallocbuff is the same address every time I run it. &mallocbuff[0] is some random address every time. I was expecting the addresses to match each other. Can anyone explain why this isn't the case?


&mallocbuff is the address of the named variable mallocbuff. &mallocbuff[0] is the address of the first element in the buffer pointed to by mallocbuff, that you allocated with malloc().


mallocbuff isn't an array, it's a pointer. It's stored completely separate from where malloc allocates.

This would give the results you expect (and as required):

int main(){
  char buf[1];
  printf("&buf     == %p\n", &buf);
  printf(" buf     == %p\n",  buf);  // 'buf' implicitly converted to pointer
  printf("&buf[0]  == %p\n", &buf[0]);

  char* mbuf = buf;
  printf(" mbuf    == %p\n",  mbuf);
  printf("&mbuf[0] == %p\n", &mbuf[0]);

  printf("\n&mbuf(%p) != &buf(%p)\n", &mbuf, &buf);

  return 0;
}

Output:

&buf     == 0x7fff5b200947
 buf     == 0x7fff5b200947
&buf[0]  == 0x7fff5b200947
 mbuf    == 0x7fff5b200947
&mbuf[0] == 0x7fff5b200947

&mbuf(0x7fff5b200948) != &buf(0x7fff5b200947)


When you take the address of mallocbuf (via &mallocbuf) you are not getting the address of the array - you are getting the address of a variable that points to the array.

If you want the address of the array just use mallocbuf itself (in the first printf()). This will return the same value as &mallocbuf[0]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜