使用malloc()后变量的大小是多少?

0 c malloc

我想了解动态内存分配的概念。我想知道分配内存后大小有什么变化。

我的代码如下。

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

int main(){
    char *s;
    printf("Size before malloc: %d\n", sizeof(s));

    s = (char*)malloc(1024 * sizeof(char));
    printf("Size after malloc: %d\n", sizeof(s));
    
    printf("Size actual: %d\n", sizeof(s) * 1024);

    s[0] = 'a';
    s[1] = 'b';
    s[2] = 'c';
    s[3] = 'd';
    printf("Size by calculation: %d", sizeof(s) / sizeof(char));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我执行此代码时,我得到如下输出。

Size before malloc: 8
Size after malloc: 8
Size actual: 8192
Size by calculation: 8
Run Code Online (Sandbox Code Playgroud)

那么为什么不在分配内存后返回 8192 作为大小呢?此外,当我将字符添加到s为什么不得到 as时4

eer*_*ika 6

所有变量的大小在其整个生命周期中都是恒定的。任何函数调用都不会改变变量的大小。

那么为什么不在分配内存后返回 8192 作为大小呢?

因为该变量是一个类型的对象char *s,并且该类型的大小在您的系统上不是 8192。