简体   繁体   中英

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

I have two structures. A pointer is assigned to one. Now I would like to output data previously entered via scanf via a function (outputAddress) with a pointer as a parameter. It works with the variables via the pointer. But how do I do that with the values from the other structure? How can I output this in the function?

#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;

}

Your datamodel is probably broken anyway. The address struct has a pointer to a person, but it often makes more sense to have it the other way around.

In your data model structAddress is associated with a person via the personPtr field. As a result, Address is a main data struct. If I understand your intention correctly, you want to print info about the person and then his/her address.

For this you need to do a couple of changes. Firstly, you should pass the Address struct to the print function, because it has all information available, including the pointer to the person. Secondly, you should access your person information using the pointer: ptrAddress->ptrPerson-><field> . Here is an example.

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.
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM