Showing posts with label typedef. Show all posts
Showing posts with label typedef. Show all posts

Monday, June 3, 2019

typdefs for pointer and function pointer and enum and struct

typedef in function pointer:




int add(int a, int b)
{
    return (a+b);
}

typedef int (*add_integer)(int, int); //declaration of function pointer

int main()
{
    add_integer addition = add; //typedef assigns a new variable i.e. 
                                //"addition" to original function "add"
    int c = addition(11, 11);   //calling function via new variable
    printf("%d",c);
    return 0;
}



Ref: https://stackoverflow.com/questions/1591361/understanding-typedefs-for-function-pointers-in-c


typedef in pointer:


The typedef may be used in declaration of a number of pointers of the same type. It does not change the type, it only creates a synonym, i.e., another name for the same type as illustrated below.
typedef float* FP; // Now FP represents float*
float x,y,z;
FP px =&x, py = &y, pz = &z ; // Use of FP
In the above code px, py, and pz are pointers initialized with addresses of x, y, and z respectively.
Illustrates use of typedef in pointer declaration.


#include <stdio.h>
void main()
{
   typedef double* Dp;
   double x = 10.5,y = 8.6, z = 12.5;
   Dp px = &x , py = &y, pz = &z;
   clrscr();
   printf("x = %.3lf,\t *px =  %.3lf\t px = %p \n", x, *px, px);
   printf("y = %.3lf,\t *py =  %.3lf\t py = %p \n", y, *py, py);
   printf("z = %.3lf,\t *pz =  %.3lf\t pz = %p \n", z, *pz, pz);
} 


Reference from:
http://ecomputernotes.com/what-is-c/function-a-pointer/typedef-in-pointer

typedef in enum:




way 1: 
enum State {Working = 1, Failed = 0}; 
way 2: 
typedef enum {false, true} boolean;
boolean error = false;
         


Reference from:
http://ecomputernotes.com/what-is-c/function-a-pointer/typedef-in-pointer

typedef in struct:



#include <stdio.h>
#include <string.h>
 
typedef struct Books {
   char title[50];
   char author[50];
   char subject[100];
   int book_id;
} Book;
 
int main( ) {

   Book book;
 
   strcpy( book.title, "C Programming");
   strcpy( book.author, "Nuha Ali"); 
   strcpy( book.subject, "C Programming Tutorial");
   book.book_id = 6495407;
 
   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);

   return 0;
}


Ref: https://www.tutorialspoint.com/cprogramming/c_typedef.htm