This blog is under construction

Saturday 6 July 2013

C program to pass structure to a function

How to do memory allocation for character double pointer?
char **type;
type = (char **)malloc(sizeof(struct char *), 10);   //equivalent to *type[10]
for (i = 0; i < 10; i++)
     type = (char *)malloc(sizeof(struct char), 10)

Above allocation is equivalent to type[10][10]

Write a C program to pass structure to a function.


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

  struct database {
        int *number;
        char **type;
  };

  /* updates the database */
  void updateDB(struct database *db, int n) {
        int i;
        char **type;

        /* allocate memory to store n numbers */
        db->number = (int *)malloc(sizeof(int) * n);

        /* allocate memory to store the type of number */
        db->type = (char **)malloc(sizeof(char *) * n);
        for (i = 0; i < n; i++) {
                db->type[i] = (char *) malloc(sizeof(char) * 10);
        }

        /* updating the database */
        for (i = 0; i < n; i++) {
                db->number[i] = i + 1;
                if (db->number[i] % 2 == 0) {
                        strcpy(db->type[i], "EVEN");
                } else {
                        strcpy(db->type[i], "ODD");
                }
        }
        return;
  }

  int main() {
        int i = 0, n;
        struct database *db;

        /* get the input n from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* allocating memory for database */
        db = (struct database *)malloc(sizeof(struct database));

        /* updating database */
        updateDB(db, n);

        /* printing the database */
        printf("Printing the Database:\n");
        for (i = 0; i < n; i++) {
                printf("%d is %s\n", db->number[i], db->type[i]);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:10
  Printing the Database:
  1 is ODD
  2 is EVEN
  3 is ODD
  4 is EVEN
  5 is ODD
  6 is EVEN
  7 is ODD
  8 is EVEN
  9 is ODD
  10 is EVEN



No comments:

Post a Comment