How to use calloc in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>

int main () {
   int size = 10;
   int *p;

   p = (int*)calloc(size, sizeof(int));

   for (int i = 0 ; i < size ; i++) {
      printf("%d ", p[i]);
   }

   free(p);
   
   return(0);
}
 
 
 
 
 
/*
run:
 
0 0 0 0 0 0 0 0 0 0 
 
*/

 



answered Dec 19, 2021 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {
    int size = 10;
    int *p;

    p = (int*)calloc(size, sizeof(int));

    srand(time(NULL));
    for (int i = 0 ; i < size ; i++) {
        p[i] = (rand() % 100) + 1; // from 1 to 100
        printf("%d ", *(p + i)); // *(p + i) == p[i]
    }

    free(p);
   
    return(0);
}
 
 
 
 
 
/*
run:
 
56 11 21 67 37 96 27 8 94 84
 
*/

 



answered Dec 19, 2021 by avibootz

Related questions

...