
malloc()函数代表内存分配,动态分配一块内存。
它保留指定大小的内存空间,并返回指向内存位置的空指针。
malloc() 函数携带垃圾值。返回的指针是void类型。
malloc()函数的语法如下 -
立即学习“C语言免费学习笔记(深入)”;
ptr = (castType*) malloc(size);
以下示例展示了 malloc() 函数的用法。
现场演示
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *MemoryAlloc;
/* memory allocated dynamically */
MemoryAlloc = malloc( 15 * sizeof(char) );
if(MemoryAlloc== NULL ){
printf("Couldn't able to allocate requested memory</p><p>");
}else{
strcpy( MemoryAlloc,"TutorialsPoint");
}
printf("Dynamically allocated memory content : %s</p><p>", MemoryAlloc);
free(MemoryAlloc);
}当执行上述程序时,会产生以下结果 -
Dynamically allocated memory content: TutorialsPoint
以上就是在C语言中,malloc函数是用来动态分配内存的的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号