c - 为什么使用 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
解决方案
Malloc is used on a pointer. You are declaring an integer
int a
. This needs to be changed toint *a
The
sizeof()
operator will not give the no of bytes allocated bymalloc
. This needs to be maintained by the programmer and typically cannot be determined directly from the pointer.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
You should always remember to
free
the memory you have allocated with mallocfree(a);
Edit The printf
format specifiers should be %zu
for a sizeof()
output. See comments below.
推荐阅读
- javascript - AngularJS - JQuery UI 是否与内置的 JQLite 一起使用
- bash - 计算bash中带有许多小数的2个数字之间的百分比增加/减少
- java - 内部类泛型 - 不兼容的类型
- javascript - 在网页上捕获签名(通过平板电脑屏幕)
- swift - Xcode NSEException,信号 SIGABRT 无法弄清楚
- jquery - JQuery - 语法
- django - Wagtail 前端的文档链接
- java - 对循环中更改的最终变量的引用
- typescript - 使用 TypeScript 进行部分应用
- vb.net - 如何增加 DataGridView 的列标题工具提示的显示时间?