Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to use calloc() to allocate memory for an array of int and initializes the storage to zero in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int *p1 = calloc(5, sizeof(int));    // allocate and zero out an array of 5 int
    int *p2 = calloc(1, sizeof(int[5])); // allocate and zero out an array of 5 int
    int *p3 = calloc(5, sizeof *p3);     // allocate and zero out an array of 5 int
 
    for (int i = 0; i < 5; i++) 
        printf("p1[%d] == %d\n", i, p1[i]);
        
    for (int i = 0; i < 5; i++) 
        printf("p2[%d] == %d\n", i, p1[i]);

    for (int i = 0; i < 5; i++) 
        printf("p3[%d] == %d\n", i, p1[i]);        
 
    free(p1);
    free(p2);
    free(p3);
    
    return 0;
}
  
/*
run:
 
p1[0] == 0
p1[1] == 0
p1[2] == 0
p1[3] == 0
p1[4] == 0
p2[0] == 0
p2[1] == 0
p2[2] == 0
p2[3] == 0
p2[4] == 0
p3[0] == 0
p3[1] == 0
p3[2] == 0
p3[3] == 0
p3[4] == 0


*/

 



answered Aug 27, 2016 by avibootz

Related questions

1 answer 179 views
1 answer 175 views
175 views asked Jul 11, 2019 by avibootz
1 answer 133 views
2 answers 257 views
1 answer 172 views
1 answer 131 views
131 views asked May 4, 2021 by avibootz
...