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.

40,003 questions

51,950 answers

573 users

How to allocate and zero out an array of N ints in C

3 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
   
int main(void) {
    int n = 5;
    int* p = calloc(n, sizeof(int)); // allocate and zero out an array of n int

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

 



answered Apr 14, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
   
int main(void) {
    int n = 5;
    int* p = calloc(1, sizeof(int[4])); // allocate and zero out an array of n int

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

 



answered Apr 14, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
   
int main(void) {
    int n = 5;
    int* p = calloc(4, sizeof *p); // allocate and zero out an array of n int

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

 



answered Apr 14, 2024 by avibootz
...