Array address and array address [0] - C language

My question is: why is the address of the array different from the address of its first position?

I'm trying to write my own malloc, but for starters, I just allocate a piece of memory and play with the addresses. My code looks something 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 it starts. & mallocbuff [0] is a random address every time. I expected the addresses to match. Can someone explain why this is not so?

+4
source share
3 answers

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

+13
source

mallocbuff is not an array, it is a pointer. It is stored completely separately from where malloc stands out.

This will produce the expected results (and as needed):

 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; } 

Conclusion:

 &buf == 0x7fff5b200947 buf == 0x7fff5b200947 &buf[0] == 0x7fff5b200947 mbuf == 0x7fff5b200947 &mbuf[0] == 0x7fff5b200947 &mbuf(0x7fff5b200948) != &buf(0x7fff5b200947) 
+8
source

When you take the address of mallocbuf (via &mallocbuf ), you do not get the address of the array - you get the address of the variable pointing to the array.

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

+4
source

Source: https://habr.com/ru/post/1307879/


All Articles