如何使用内存在C中遍历一个结构?

问题描述 投票:0回答:3

我对C lang非常友好,一直在从事我一直坚持的项目。这是下面的代码

#include <stdio.h>

typedef struct{
int age;
int zipcode;
} person;

int main()
{
int age = 45;
int zipcode = 45035;
person person_1 = {.age = age, .zipcode = zipcode};

age = 89;
zipcode = 20941;
person person_2 = {.age = age, .zipcode = zipcode};

age = 41;
zipcode = 39290;
person person_3 = {.age = age, .zipcode = zipcode};

age = 50;
zipcode = 92749;
person person_4 = {.age = age, .zipcode = zipcode};


age = 13;
zipcode = 78500;
person person_5 = {.age = age, .zipcode = zipcode};

person* y[5] = {&person_1, &person_2, &person_3, &person_4, &person_5};


int* pt = &y;
printf("this is addr %d\n", y);
printf("this is pt %d\n", *pt);
for(int i =0; i < 5; i++)
{
    person current = pt;
    printf("%d\n", current.age);
    printf("%d\n", current.zipcode);

    pt+=1;
}

}

我想对指针变量pt做一些事情。我试图访问我的struct arr中第一项的存储位置,以便可以在数组中移动并显示其中的所有内容。我知道在这种情况下不使用指针可能会更简单,但是我将在文件中使用此代码,因此我认为这样做会使整个过程更容易。

c arrays pointers memory-management
3个回答
0
投票

这里有一些更新可能使您更接近所需的内容:


0
投票

如果您询问如何遍历结构的字段,则不能这样做。但由于


0
投票

[您真的[可能]确实不希望额外的间接级别。如果保持简单,它将更好地扩展]

© www.soinside.com 2019 - 2024. All rights reserved.