结构指针数组的访问元素

时间:2013-06-14 13:24:45

标签: c arrays structure

我想访问结构指针数组的元素,但我不知道如何访问它。

#include<stdio.h>
int main()
{
struct hash
{
int pages;
int price;
};
struct hash *h[5]={1,2,3,4,5};//array of pointer to structure
printf("value =%d\n",h->pages);
// want to access and also tell me how to data will be write
}
  How we will access the element I tried it through pointer but it's showing error

3 个答案:

答案 0 :(得分:1)

这是一个编译的示例。也许这有助于你开始。

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

struct hash
{
int pages;
int price;
};

struct hash h[5]=
{
    { 1, 1 },
    { 2, 2 },
    { 3, 3 },
};

int main(void)
{
    printf("pages: %d\n", h[0].pages);
    printf("pages2: %d\n", h[1].pages);

    return EXIT_SUCCESS;
}

答案 1 :(得分:1)

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

int main()
{
    struct hash {
        int pages;
        int price;
    };
    struct hash *h[2];
    h[0] = malloc(sizeof(struct hash));
    h[0]->pages = 1;
    h[0]->price = 2;
    h[1] = malloc(sizeof(struct hash));
    h[1]->pages = 3;
    h[1]->price = 4;
    printf("value = %d\n", h[0]->pages);
}

答案 2 :(得分:1)

我首先建议尝试让stuct hash *h;指向单个变量。一旦有效,你应该在它上面构建struct hash *h[5]数组。