首页 > 解决方案 > 为什么使用 malloc()?为什么变量的大小没有增加?

问题描述

根据我的教师的回答malloc动态分配内存,那么为什么输出显示分配给普通变量和malloc();. 我是编程新手,所以我想您会以新手可以理解的方式回答我的问题。

#include<stdio.h>

int main()
{
    int a,b;
    a = (int *) malloc(sizeof(int)*2);
    printf("The size of a is:%d \n",sizeof(a));
    printf("The size of b is:%d \n",sizeof(b));
    return 0;
}

输出:

The size of a is:4
The size of b is:4

标签: c

解决方案


  1. Malloc is used on a pointer. You are declaring an integer int a. This needs to be changed to int *a

  2. The sizeof() operator will not give the no of bytes allocated by malloc. This needs to be maintained by the programmer and typically cannot be determined directly from the pointer.

  3. For int *a, sizeof(a) will always return the size of the pointer,

    int *a;
    printf("%zu\n",sizeof(a));   // gives the size of the pointer e.g. 4
    a = malloc(100 * sizeof(int));
    printf("%zu\n",sizeof(a));    // also gives the size of the pointer e.g. 4
    
  4. You should always remember to free the memory you have allocated with malloc

    free(a);
    

Edit The printf format specifiers should be %zu for a sizeof() output. See comments below.


推荐阅读