【问题标题】:Access element of array of pointer of structure结构指针数组的访问元素
【发布时间】:2013-06-11 03:59:54
【问题描述】:

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

#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

【问题讨论】:

  • 这 1. 无法编译,2. 没有任何意义,3. 难以理解且不完整:“它显示错误”甚至对任何试图回答您的问题的人都没有帮助。
  • 2.5 年的 C 语言经验? o_0
  • 散列结构的指针必须指向散列结构或散列结构的指针。您将指针值设置为 1,2,3,4,5,它们只是可以在内存中任何位置的数据。

标签: c arrays structure


【解决方案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;
}

【讨论】:

    【解决方案2】:
    #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);
    }
    

    【讨论】:

      【解决方案3】:

      我首先建议尝试让stuct hash *h; 指向单个变量。一旦它工作了,你应该在它的基础上让struct hash *h[5] 的数组工作。

      【讨论】:

        猜你喜欢
        • 2011-06-04
        • 2017-01-04
        • 2020-11-05
        • 1970-01-01
        • 2013-05-26
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        • 2014-11-05
        相关资源
        最近更新 更多