c - 返回 mallocatted 数组的大小

标签 c arrays pointers malloc dynamic-memory-allocation

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

int main()
{
    int n;
    int *num=malloc(sizeof(int)*n);
    printf("Enter how many numbers:\n");
    scanf("%d",&n);
    printf("Enter numbers:\n");
    for(int i=0;i<n;i++)
    {
        scanf("%d",num+i);    

    }

    for(int j=0;j<n;j++)
    {
        printf("%d\n",*(num+j));    

    }

    return 0;
}

即使我没有在这里初始化 n,malloc 如何工作?有什么方法可以检查用 malloc 分配的数组的大小?

最佳答案

您可以在分配时将整个长度加到 1,并在第一个元素中保留 n 作为长度。如果您想从数组中获取某些内容,只需将 1 添加到索引即可。

关于c - 返回 mallocatted 数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54956122/

相关文章:

c - 通过使用一系列指针从结构访问字符串

javascript - 如何在javascript中随机制作音频文件数组

ruby - 数组的未定义方法 `each '

c - 用C语言识别俄罗斯方 block

c - 如何在 C 中使用结构体、指针和函数?

c - 错误: dereferencing pointer to incomplete type ‘struct student’ root->next->student_number = 17;

c++ - 将 char 指针传递给另一个函数 : blank value. c++

c++ - 统一初始化int* : how can it be forced?

c - 当我将指针初始化为NULL时,运行结果很奇怪

C 段错误 :11