zoukankan      html  css  js  c++  java
  • C基础知识(13):内存管理

    如果事先不知道数组的具体长度,则需要动态分配内存。下面是例子。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 int main() {
     6     // 如果预先不知道需要存储的文本长度,则需要定义一个指针,后续再根据需求来分配内存
     7     char *str;
     8     // 在内存中动态地分配num个长度为size的连续空间,并将每一个字节都初始化为0
     9     str = malloc(30 * sizeof(char)); // 或 str = calloc(200, sizeof(char));
    10     if (str == NULL) {
    11         fprintf(stderr, "Error - unable to allocate required memory
    ");
    12     } else {
    13         strcpy(str, "I'm a Java programmer.");
    14     }
    15     // 假设存储更大的描述信息要使用realloc,该函数重新分配内存,把内存扩展到newsize(50)
    16     str = realloc(str, 100 * sizeof(char));
    17     if (str == NULL) {
    18         fprintf(stderr, "Error - unable to allocate required memory
    ");
    19     } else {
    20         strcat(str, " But I have to learn C (TT)!");
    21     }
    22     printf("%s
    ", str); // I'm a Java programmer. But I have to learn C (TT)!
    23     // 使用 free() 函数释放内存
    24     free(str);
    25 
    26     return 0;
    27 }
  • 相关阅读:
    Scrapy中间件
    Scrapy简介
    Scrapy解析器xpath
    postman
    yarn
    brew 安装 yarn 时候失败
    immutability-helper 用途+使用方法
    js 正则
    react redux 应用链接
    react 事件传参数
  • 原文地址:https://www.cnblogs.com/storml/p/7826676.html
Copyright © 2011-2022 走看看