Search code examples
cdynamic-memory-allocationcalloc

Can't allocate an array dynamically of size 10


I'm trying to dynamically allocate an array of size 10. But when I print the elements of the array, I get value of 8 elements. (I'm working on the editor provided by hackerrank.)

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    char *s = malloc(1024*sizeof(char));
    scanf("%[^\n]", s);
    int* freq = (int*)calloc(10,sizeof(int));
    for(int i=0;i<sizeof(freq);i++)
        printf("%d ",freq[i]);
    }

Expected output:

0 0 0 0 0 0 0 0 0 0

The output I'm getting:

0 0 0 0 0 0 0 0 

Why am I not getting the expected output?


Solution

  • sizeof(freq) will return the size of int * in bytes in your machine which happens to be 8. Just use i < 10.