美文网首页
C动态分配内存

C动态分配内存

作者: 叩首问路梦码为生 | 来源:发表于2024-04-22 14:41 被阅读0次

    例题:开辟int类型空间,赋值为20并输出

    //
    // Created by linux on 4/22/24.
    //
    #include <stdio.h>
    #include <stdlib.h>  //动态分配堆内存需要导入
    //动态分配内存
    int main() {
        int *p1=NULL;
        p1=(int *) malloc(sizeof(int));
        if(p1==NULL){
            printf("malloc error \n");
            return -1;
        }
        //分配成功
        *p1=20;
        printf("Value of *p1: %d\n", *p1);
        //分配结束后记得释放,否则会长时间占用堆内存 ,生命周期直到你手动free释放
        free(p1);
        p1=NULL;  //释放内存之后记得赋值NULL 空指针
        return 0;
    }
    

    例题:开辟字符类型空间,赋值为B并输出

    当然!下面是一个为字符动态分配内存并为其分配值“B”,然后打印该字符的示例:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char *char_ptr = (char *)malloc(sizeof(char)); // Allocate memory for a character
        
        if (char_ptr == NULL) {
            printf("malloc error\n");
            return -1;
        }
        
        *char_ptr = 'B'; // Assign the character 'B' to the allocated memory
        
        printf("Value of *char_ptr: %c\n", *char_ptr); // Print the character
        
        free(char_ptr); // Free the allocated memory
        
        char_ptr = NULL; // Set the pointer to NULL
        
        return 0;
    }
    

    此代码动态为字符分配内存,为其分配“B”,打印该字符,释放分配的内存,并将指针设置为 NULL。


    include <stdlib.h>的作用:

    <stdlib.h>是C标准库中的头文件。它代表“标准库”,提供多种通用函数,包括内存分配、进程控制、转换等。

    以下是 提供的一些常用函数和类型<stdlib.h>

    1. 内存分配函数

      • malloc():动态分配内存。
      • calloc():为数组分配内存并将其所有位初始化为零。
      • realloc():更改先前分配的内存块的大小。
      • free():释放动态分配的内存。
    2. 退出功能

      • exit():终止调用过程。
      • abort():导致程序异常终止。
    3. 伪随机数生成器

      • rand():生成伪随机数。
      • srand():为随机数生成器播种。
    4. 环境功能

      • system():执行由字符串指定的命令。
    5. 字符串到数字的转换

      • atoi()atol()atoll():分别将字符串转换为整数、长整型或长长整型。
      • atof():将字符串转换为浮点数。

    还有许多其他人。

    <stdlib.h>是 C 编程中必不可少的头文件,提供内存管理、处理程序终止和生成随机数等任务的函数。

    相关文章

      网友评论

          本文标题:C动态分配内存

          本文链接:https://www.haomeiwen.com/subject/gqzbxjtx.html