DEV Community

loading...

Structures and functions in C

mikkel250
I've been tinkering with computers since I was a teen. I'm currently pivoting from my current role as Tech Support manager to Full Stack Web Developer. I'm actively seeking employment in the field.
・2 min read

Structures as arguments to functions

To pass a structure into a function, use the keyword struct, the name of the structure, and the name of the variable you wish to use inside the function. The members of the structure are then available using dot notation inside the function.

struct Family {
  char name[20];
  int age;
  char father[20];
  char mother[20];
};

// use a function to compare two family members and check if they're siblings
bool siblings(struct Family member1, struct Family member2) {
  // if they have the same mother (i.e. the names are equal), then return true
  if(strcmp(member1.mother, member2.mother) == 0)
  {
    return true;
  }
  else
  {
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

Pointers to structures as function arguments

It is better to use pointers as function arguments, as mentioned before, to avoid the computational load and memory space of having to copy all the data that is being passed in (because C passes by reference). With pointers, only the address is copied, so computational and memory load are minimal.

bool siblings(struct Family *pointerToMember1, struct Family *pointerToMember2)
{
  if(strcmp(pointerToMember1->mother, pointerToMember2->mother) == 0)
  {
    return true;
  }
  else
  {
    return false;
  }
}

// Alternative: don't allow the members of struct to be changed by the function
// use the const modifier (in front of the pointer) if you don't want to allow changes to
// be made to the members of the struct
bool siblings(Family const *pointerToMember1, Family const *pointerToMember2)
{
  if(strcmp(pointerToMember1->mother, pointerToMember2->mother) == 0)
  {
    return true;
  }
  else
  {
    return false;
  }
}

// Another alternative: don't allow the pointer address to change
// this is less useful because it is a copy of the address (passed by value),
// but if you wanted to, put the asterisk in front of the const keyword as below
bool sibling(Family *const pointerToMember1, Family *const pointerToMember2)
{
  // ... your code
}
Enter fullscreen mode Exit fullscreen mode

The ability to return a structure from a function is very valuable because it allows you to return more than 1 piece of data. Just remember to take care when using pointers because the data in the original structure can be permanently changed by the function. To prevent this, use the const keyword in front of the pointer as in the second example in the code above Family const *pointerToMember1.

Discussion (0)