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
...