【问题标题】:Why memory is not allocated?为什么没有分配内存?
【发布时间】:2020-12-18 08:03:09
【问题描述】:

我需要构建一个函数,该函数将内存分配给一个指针以形成一个数组,但无论我尝试什么,它都不会分配内存。

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

void alocare(int **a,int n)
{
   *a = (int*) malloc(n*sizeof(int));
}

int main()
{
     int *a ,*b,*c,n,m,k;
    printf("Insert the number of elements for the first array:\n");
    scanf("%d",&n);
    printf("Insert the number of elements for the second array:\n");
    scanf("%d",&m);
    
    printf("Number of bytes ocupied by a before alloc(): %d\n",sizeof(a));
    printf("Number of bytes occupied by b before alloc(): %d\n",sizeof(b));
    alocare(&a,n);
    alocare(&b,m);
    printf("Number of bytes ocupied by a after alloc(): %d\n",sizeof(a));
    printf("Number of bytes ocupied by b after alloc(): %d\n",sizeof(a));
    return 0;
}

它在两个printf中显示的大小在分配之前和之后都是4,我不明白为什么 谢谢!

【问题讨论】:

  • 什么是...sizeof (a_pointer)?

标签: c dynamic-memory-allocation


【解决方案1】:

sizeof(a) 返回a 类型的大小。由于a 是一个指针,它的大小始终为4(在您的平台中;在其他平台中可能为8 或其他)。这个大小永远不会改变:它对你的程序来说是一个常数。

除非您自己保存,否则无法知道指针后面分配的内存大小。

【讨论】:

    【解决方案2】:

    内存已分配。

    但是,如果只使用 sizeof(a),它将返回“指针大小”而不是“整个数组内存的大小”

    您可以在 Windows 中使用“_msize”来查找指针内的内存大小。

    _msize // in windows
    malloc_size // in MacOS
    

    它适用于 Microsoft Visual Studio

    【讨论】:

    • 这些函数是非标准的,永远不要使用。
    • 也没有理由在您的答案中包含纯文本输出作为图像。将文本复制/粘贴为文本要容易得多。
    • @Jabberwocky 调试时除外
    猜你喜欢
    • 2021-04-16
    • 2019-11-18
    • 2021-10-03
    • 2014-04-24
    • 2020-01-10
    • 2020-07-18
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多