开发者

Intrinsical difference between struct and array in C

开发者 https://www.devze.com 2023-03-30 17:06 出处:网络
everyone. Here is a test program I wrote. #include <stdio.h> #include <stdlib.h> typedef struct _item {

everyone.

Here is a test program I wrote.

#include <stdio.h>
#include <stdlib.h>

typedef struct _item {
    int value;
} item , *pItem;

typedef struct _itemcontainer {
    pItem i;
} itemcontainer, *pItemcontainer;

int main(void) {
    item i;
    i.value = 1;

    pItem pi = &i;
    pItem* ppi = &pi;

    itemcontainer ei = {&i};
    pItem* pei = (pItem*)(&ei);

    pItem api[1] = {&i};

    printf("First case: %d\n", (*ppi)->value);
    printf("Second case: %d\n", (*pei)->value);
    printf("Third case: %d\n", (*api)->value);


    return EXIT_SUCCESS;
}

The three printf functions' results are the same value, i.e. 1. From the code, the initialization of variable ei and api are both {&i}. So I guess pItem* pei = (pItem*)ei should work, however it failed. Could any one tell me the difference between ei and api? It seems to be related with h开发者_如何学Pythonow the compiler deal with struct and array, which I am not good at. I need a concrete explanation. Thanks in advance.

Best Wishes

Jfhu


The difference is that the array name is implicitly converted to a pointer to its first element in most situations, while the name of an object of struct type is not.

The expression pItem* pei = (pItem*)api; would compile because it is equivalent to pItem* pei = (pItem*)(&api[0]);

The expression pItem* pei = (pItem*)ei; would not compile because it attempts to cast an object of struct type (a value) to a pointer to some unrelated type.

The expression you used, pItem* pei = (pItem*)(&ei); creates a pointer to the struct object and reinterprets it to mean pointer to pItem. Since pItem is the first element of the struct, it is located at the same memory address as ei, and this works. (this is even guaranteed by the standard, §6.7.2.1/13: "pointer to a structure object, suitably converted, points to its initial member")

0

精彩评论

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

关注公众号