Structure in C programming


Advertisements

Share



Learn C structure declaration, initilization, array of structures, typedef, passing structure or structure pointer to function, function returning structure or structure pointer.

What is structure in C?

A structure is a collection of one of more variables grouped together under a single name for convenient handling. Structure is another derived data type like arrays and strings.

The variables in a structure are called members and members may have any basic type such as int, char, float etc. and derived types such as arrays, strings or other structures.

struct keyword is used to define a structure variable. A semicolon is put at the end of each structure definition. Following code snippet shows how to define a structure books.

struct books
{
  char title[LEN];
  char author[LEN];
  float value;
}book1; /* note semi-colon here */

struct variables are declared by a combination of the keyword struct and the name of the struct. You can define a structure variable in the structure definition itself like we defined structure variable book1 in the above code or separately in another statement like struct book book1;.

structures are generally defined in header files along with function prototypes. You can define them at the top of .c file as well. dot(.) operator is used to initialize and access structure members. For example member title of the structure books can be initialized and accessed by using book1.title.

Similar to arrays an array of structures can be declared using square brackets. For example an array of books can be declared as struct books book1[3];.

There are few other ways a c structure can be initialized. For example a structure books we discussed in this section having 2 array members and one float member can be initialized as below.

struct books book1 =
{
      "C Illustrations",
      "Ravindra Majhi",
      2.03
};

Another way of initializing a structure is as below.

struct books book1 =
{
  .title = "C Illustrations",
  .author = "Ravindra Majhi",
  .value = 2.03
};

Similar to dot(.) operator arrow(->) operator can used to initialize and access members of a structure as shown below. Observe that to use arrow operator we need to declare the pointer variable of structure book. Also note that by just declaring a pointer variable of struct book there is no memory allocated at b1. To allocate some memory at b1 we need to use malloc.


struct book{
  int pages;
};
struct book *b1 = malloc(sizeof(struct book));
b1->pages = 90;

typedef keyword

typedef keyword is used to create short names for the basic and derived data types. All you have do is provide the old type name followed by the type that should represent it throughout the code. Typedefs provide more clarity to the program and make it easier to make any change to the underlying data types that are used in the program. For example if you define a typedef like below.

typedef unsigned int size_t;

In the above code you can write size_t as short hand without writing unsigned int the full statement again and again in the program. Similarly you can write the following code to write a short hand notation as BOOK for books structure.

typedef struct books
{
    char title[LEN];
    char author[LEN];
    float value;
}BOOK;

BOOK is now a type that can be declared without "struct books" in front of it like BOOK book1;.

Passing structure to function

Let's write a program as below to demonstrate passing structure to a function


#include "stdio.h"
#include "stdlib.h"
typedef struct books
{
  int pages;
}BOOK;
void passStruct(BOOK *in, BOOK *out);
int main()
{
  BOOK book1, *book2 = malloc(sizeof(BOOK));
  book1.pages = 100;
  book2->pages = book1.pages;
  printf("book1 has:%d pages, book2 has:%d pages\n", book1.pages, book2->pages);
  passStruct(&book1, book2);
  printf("book1 has:%d pages, book2 has:%d pages\n", book1.pages, book2->pages);
  return 0;
}
void passStruct(BOOK *in, BOOK *out)
{
  in->pages = 200;
  out->pages = in->pages;
}
Program output:
===============
$ gcc prog.c
$ ./a.out
book1 has:100 pages, book2 has:100 pages
book1 has:200 pages, book2 has:200 pages
$

In the above program we updated the number of pages in the book1 and book2 structure using a function passStruct.

Function returning pointer to struct

A function can return a pointer to a structure. Also we can remove the allocated memory using free library function. Let's write a program as below to demonstrate Function returning pointer to struct.


#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct book
{
  int no_pages;
  char author[20];
  char title[20];
};
typedef struct book BOOK;
struct book *entry_book(int pages, char *auth, char title[]);
void book_details(struct book *ptr);
void book_destory(struct book *ptr);
int main() {
  BOOK *ptr = entry_book(1228, "Balmiki", "Ramayan");
  book_details(ptr);
  book_destory(ptr);
  return 0;
}
struct book *entry_book(int pages, char *auth, char title[]) {
    struct book *who = malloc(sizeof(struct book));
    if(who == NULL) {
      printf("Memory allocation failed\n");
      exit(0);
    }
    who->no_pages = pages;
    strcpy(who->author,auth);
    strcpy(who->title,title);
    return who;
};
void book_details(struct book *ptr)
{
 printf("No of pages in book %d\n",ptr->no_pages);
 printf("Author is %s\n",ptr->author);
 printf("Title is %s\n",ptr->title);
}
void book_destory(struct book *ptr)
{
    if(ptr == NULL) {
      printf("Memory allocation failed\n");
      exit(0);
    }
    free(ptr);
}
Program output:
===============
$ gcc prog.c
$ ./a.out
No of pages in book 1228
Author is Balmiki
Title is Ramayan
$

In the above program we have defined structure book and created BOOK as short name for struct book. We have defined entry_book function to entry the book details. entry_book function returns a pointer to the structure after entering book data. Function book_details takes a pointer to structure book and displays the details of the book. Function book_destroy will free the memory allocated to store the details of book. Once memory is freed using free you will not be able to access the content of the book.


Function pointers with structures


#include "stdio.h"
void myFunc();
void myNextFunc();
void (*fptr)();
struct sPtr{
  char a[30];
  void (*ptr)();
};
struct sPtr a[] = {
    {"testMyFunc",myFunc},
};
typedef void (*funcPtr)();
void (*func)();
struct tPtr{
  char a[30];
  funcPtr handler;
};
struct tPtr b[] = {
    {"testMyNextFunc",myNextFunc},
};
int main(int argc,char *argv[]){
  fptr = a[0].ptr;
  (*fptr)();
  func = b[0].handler;
  (*func)();
  return 0;
}
void myFunc(){
  printf("myFunction print\n");
}
void myNextFunc(){
  printf("myNextFunc print\n");
}
Program output.
=====================
$ gcc prog.c
$ ./a,out
myFunction print
myNextFunc print
$

In above program we have declared two function pointers fptr, tptr and two structures sPtr, tPtr. We have created array of structures sPtr and tPtr. Inside main function we have initialized fptr first and then called it. Then we called fptr and func function pointers inside main function.

Exercises, Solutions

Medium
High
High
High
High
High
Medium

Want to contribute a new article? Write and upload your article information .
Share

 Articles

 C Programming

 Linux Software

 Test your skills:online tests

 C Programming

 Python Programming

 Linux Software

 Quantitative Aptitude

 Embedded System Software

 Search Code Snippets

 Popular C search examples

 Popular C search MCQs