【问题标题】:Can't allocate an array dynamically of size 10 [duplicate]无法动态分配大小为 10 的数组 [重复]
【发布时间】:2020-06-26 17:32:51
【问题描述】:

我正在尝试动态分配一个大小为 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 

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

【问题讨论】:

  • sizeof(freq) 是指针的大小,而不是指针的大小,您知道数组的长度,您只需将10 传递给calloc
  • sizeof 返回指针本身的大小(以字节为单位),而不是它指向的数组元素的数量。无法获取动态分配数组的大小。

标签: c dynamic-memory-allocation calloc


【解决方案1】:

sizeof(freq) 将在您的机器中返回 int * 的大小(以字节为单位),恰好是 8。只需使用 i &lt; 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2021-01-15
    • 2013-09-05
    相关资源
    最近更新 更多