Passes and returns structures - C Structure

C examples for Structure:Structure Value

Description

Passes and returns structures

Demo Code

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

#define NLEN 30//ww  w  .j  a v  a  2  s  . co  m
struct NameStructure {
    char fname[NLEN];
    char lname[NLEN];
    int letters;
};

struct NameStructure getinfo(void);
struct NameStructure makeinfo(struct NameStructure);
void showinfo(struct NameStructure);
char * s_gets(char * st, int n);

int main(void)
{
    struct NameStructure person;
    
    person = getinfo();
    person = makeinfo(person);
    showinfo(person);
    
    return 0;
}

struct NameStructure getinfo(void)
{
    struct NameStructure temp;
    printf("Please enter your first name.\n");
    s_gets(temp.fname, NLEN);
    printf("Please enter your last name.\n");
    s_gets(temp.lname, NLEN);
    
    return temp;
}

struct NameStructure makeinfo(struct NameStructure info)
{
    info.letters = strlen(info.fname) + strlen(info.lname);
    
    return info;
}

void showinfo(struct NameStructure info)
{
    printf("%s %s, your name contains %d letters.\n",
           info.fname, info.lname, info.letters);
}

char * s_gets(char * st, int n)
{
    char * ret_val;
    char * find;
    
    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        find = strchr(st, '\n');   // look for newline
        if (find)                  // if the address is not NULL,
            *find = '\0';          // place a null character there
        else
            while (getchar() != '\n')
                continue;          // dispose of rest of line
    }
    return ret_val;
}

Result


Related Tutorials