如何使用malloc在C中初始化char数组?

问题描述

我尝试使用malloc分配一个char数组,但大小始终为“ 8”:

char *d = malloc(2356 << 1);
printf("size of *d: %d\n",sizeof(d));

output: size of *d: 8

char *d = malloc(2356 * sizeof(*d);
printf("size of *d: %d\n",sizeof(d));

output: size of *d: 8

char *d = malloc(2356 * sizeof(char));
printf("size of *d: %d\n",sizeof(d));

size of *d: 8

请帮助我,我的代码有什么问题?

谢谢!

解决方法

您无法使用sizeof()方法找到malloc分配的内存大小。但是,相反,有一些特定于操作系统的功能可用于查找分配的大小。

如果您在Windows中,则可以在_msize()头文件中使用malloc.h函数。它将返回字节大小。

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

int main(){
    char *d = malloc(2356 << 1);
    printf("size of *d: %d\n",_msize(d));
    //size of *d: 4712

    char *e = malloc(2356 * sizeof(*e));
    printf("size of *d: %d\n",_msize(e));
    //size of *d: 2356

    char *f = malloc(2356 * sizeof(char));
    printf("size of *d: %d\n",_msize(f));
    //size of *d: 2356
    return 0;
}

您可以在以下线程中找到有关其他特定于操作系统的功能的更多信息:Determine size of dynamically allocated memory in C

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...