无法动态分配大小为10的数组

问题描述 投票:0回答:1

我正在尝试动态分配大小为10的数组。但是,当我打印数组的元素时,我得到8个元素的值。 (我正在使用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]);
    }

预期输出:

0 0 0 0 0 0 0 0 0 0

我得到的输出:

0 0 0 0 0 0 0 0 

为什么我没有得到预期的输出?

c dynamic-memory-allocation calloc
1个回答
2
投票

[sizeof(freq)将返回计算机中int *的大小,以字节为单位,恰好是8。只需使用i < 10

© www.soinside.com 2019 - 2024. All rights reserved.