通过以指针作为参数的函数输出结构的值

Output of values of a struct via a function with a pointer as a parameter

我有两个结构。一个指针被分配给一个。 现在我想输出以前通过 scanf 输入的数据,通过函数(outputAddress)以指针作为参数。 它通过指针与变量一起工作。但是我如何使用其他结构的值来做到这一点呢?我怎样才能在函数中输出这个?

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

struct structPerson
{
char name[30];
char forename[50];
int age;
};

struct structAddress
{
int zip;
char location[35];
char street[40];
int hNumber;
struct structPerson *ptrPerson;
};

void outputAddress(struct structPerson *ptrPerson)
{
printf("\n\nOutput Address: \n");
printf("ptrPerson->name: %s", ptrPerson->name);
printf("\nptrPerson->forename: %s", ptrPerson->forename);
return;
}

int main()
{
struct structPerson person1;
struct structAddress address1;
address1.ptrPerson = &person1;

printf("Location: ");
scanf("%s", &address1.location);
printf("Zip: ");
scanf("%d", &address1.zip);

printf("\nName: ");
scanf("%s", &address1.ptrPerson->name);
printf("Forename: ");
scanf("%s", &address1.ptrPerson->forename);

printf("\nOutput: %d %s %s\n", address1.zip, address1.location, address1.ptrPerson->name);
// strcpy( address1.location, "");
//  printf("structAddress1: %d %s\n", address1.zip, address1.location);


outputAddress(&person1);
return 0;

}

无论如何,您的数据模型可能已损坏。地址结构有一个指向人的指针,但反过来通常更有意义。

在您的数据模型中,structAddress 通过 personPtr 字段与一个人相关联。因此,A​​ddress 是一个主要的数据结构。如果我正确理解你的意图,你想打印有关此人的信息,然后是 his/her 地址。

为此,您需要做一些更改。首先,您应该将 Address 结构传递给 print 函数,因为它具有 all 可用信息,包括指向该人的指针。其次,您应该使用指针访问您的个人信息:ptrAddress->ptrPerson-><field>。这是一个例子。

void outputAddress(struct structAddress *ptrAddress)
{
printf("\n\nOutput Address: \n");
// use ptrAddress->ptrPreson to accesss person information
printf("ptrPerson->name: %s", ptrAddress->ptrPerson->name);
printf("\nptrPerson->forename: %s", ptrAddress->ptrPerson->forename);

// use ptrAddress-> to access address fields.
printf("\nptrAddress->zip: %d", ptrAddress->zip);
...
return;
}

int main() {
   ...
   outputAddress(&address1); // << use address1 here.
   ...
}