C prog: printing values from array of structures

Click For Summary
The discussion centers on a C programming function designed to print values from an array of structures, specifically focusing on how to print a middle name as just the first initial. A solution was provided to access the first character of the middle name using printf("%c", arr[0].pers_name.middle[0]). The conversation then shifted to modifying the function to handle cases where a middle name may or may not be present, with suggestions for looping through the array and conditionally formatting the output. Participants discussed the concept of passing structures by value versus by reference, clarifying that passing by value copies the entire structure, while passing by reference uses pointers for efficiency. The thread concludes with a deeper understanding of these concepts and their implications in function design.
  • #31
Your function should look like this:

PHP:
void print_name(struct pers_info record) {
    ...
}

And the code calling it should look like:

PHP:
for (int n=0;n<5;n++)
   print_name(arr[n]);

Passing a struct by value is no different than passing any other kind of variable by value.

- Warren
 
Computer science news on Phys.org
  • #32
print_names(struct pers_info arr[n]);

You don't need to include the type when passing an argument (except for type casts, which is not what's required here).
 
  • #33
chroot said:
Your function should look like this:

PHP:
void print_name(struct pers_info record) {
    ...
}
record? Does that mean one of the individual structures I made? thanks. Record isn't a keyword is it?
 
  • #34
record is a keyword in Pascal (I think), not in C though.

In chroot's example, it's just the name of the argument.
 
  • #35
When you create a function, you can call the variables it receives by any names you'd like. Even if the calling function referred to a hunk of data as arr[n], the called function can choose to call that incoming hunk of data anything it wants. In this case, I chose the word 'record' to refer to the variable being passed into the print_name function. It's not a reserved word in C, and means, well, nothing -- you can call it aStudent if you want, or theThingy, too.

- Warren
 
  • #36
HOLY COW! IT'S WORKING! Here's the function.

void print_names(struct pers_info record)
{
printf("%s -- %s \n", record.pers_name.last, record.ssn);
}
 
  • #37
Thank You! :biggrin: :biggrin: :biggrin:

This the output:

Adams -- 123456123
Burke -- 623001200
Cooper -- 423456999
Dodd -- 327856909
Eggwhite -- 563456929
Press any key to continue
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 29 ·
Replies
29
Views
3K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 1 ·
Replies
1
Views
1K