Search code examples
clinuxmalloccalloc

How to use calloc to init struct


I have struct

struct Person
{
    char name[50];
    int citNo;
    float salary;
};

Now I do this code:

struct Person* p = malloc (sizeof(struct Person));
memset (p,0x00,sizeof(struct Person));

now I want to convert that to calloc (clean code) , how can I do that?

struct Person* p = calloc(sizeof(struct Person) ,1); 

Or maybe put 1 it's not correct? what is the right way?


Solution

  • calloc() description from man7

     #include <stdlib.h>
     void *calloc(size_t nelem, size_t elsize);
    

    The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0. The order and contiguity of storage allocated by successive calls to calloc() is unspecified. The pointer returned if the allocation ...

    I encourage you to keep reading in the link man7_calloc.

    now after reading the description above, calling calloc seems easy to me: in your case we allocating array of one struct person

    struct Person* p = NULL;
    struct Person* p = calloc(1, sizeof(struct Person)); 
    

    you must check the return value of calloc(if calloc succedd to allocate, like malloc):

    if(p == NULL){
      puts("calloc failed");
      ...
      ...
    }