简体   繁体   中英

C: pointer to array != pointer to &array[0]?

Suppose I have two arrays:

uint8_t buf1[10];
uint8_t buf2[20];

I now want to create an array of these arrays, eg,

uint8_t *buffers[] = {buf1, buf2};

When I look at the buffers variable in the debugger, however, I see that its two elements do not point to any elements of buf1 and buf2 , but look like random values (maybe the contents of buf1 / buf2 ?). Also, when dereferencing, eg,

uint8_t x = *(buffers[0] + 1);

the programs throws a bus error.

If I change the definition to

uint8_t *buffers[] = {&buf1[0], &buf2[0]};

everything is alright.

Why is there a difference? I always thought that array and &array[0] are equivalent?! What is the correct type of buffers to make definition 1 work?

EDIT: OK, I goofed up. There is in fact no difference between definition 1 and 2. I'm not really sure what change I did to see the correct values, but I do have a screenshot.

Anyway, I now know the answer to my question why the pointers are all bad, but you couldn't know because I stripped an important detail from the question.

I added __attribute__((section(".foo"))) to the definition of buffers , and that segment foo is uninitialized . Of course the values are random!

Sorry for wasting your time. :-)

At onlinegdb the following code:

#include <stdint.h>

uint8_t buf1[10];
uint8_t buf2[20];
uint8_t* buffers1[] = {buf1, buf2};
uint8_t* buffers2[] = {&buf1[0], &buf2[0]};

int main()
{
    uint8_t x1 = *(buffers1[0] + 1);
    uint8_t x2 = *(buffers2[0] + 1);

    return 0;
}

at the return statements has the following state:

在此处输入图像描述

Which seems to do what you expect, but not what you describe. How does this test differ from yours?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM