zoukankan      html  css  js  c++  java
  • 内存的动态分配

    void *malloc(unsigned int)函数包含在<stdlib.h>头文件中,void *  //泛型指针,其返回值为指针可以付给任何类型

    malloc(1000);   malloc ( n );     (float *)malloc(n*sizeof(float));   (int  *)malloc(n*sizeof( int ));等等都代表开辟了一个内存空间

    将该空间的首地址赋予指针,注意其类型一致例如:

    char *p;
    p= (char *)malloc(n*sizeof(char));


    /*void *malloc(unsigned int)

    void *  //泛型指针,其返回值为指针可以付给任何类型
    int main(void)
    {
    char *p=malloc(1000);  //开辟的堆空间
    p[0]; //所开辟空间的第一个字节
    p[1];  //第二个字节
    int *q=malloc(1000);
    q[0];  //100z字节的前四个字节
    q[1];   //第五至第八字节
    }
    #include<stdio.h>
    #include<stdlib.h>
    int main(void)
    {
    char *p=malloc(1000);
    if(p == NULL)  //相当于 if(!p)
    perror("malloc");
    exit(-1);  //
    free(p);    //将开辟堆对空间释放,该空间可以再次被申请
    return 0;


    }
    //编译系统会根据变量的声明来开辟内存空间
                         
                           栈空间  静态内存分配  其大小编译时决定
                           堆空间  动态内存分配  其大小运行时决定
                              动态                   静态
                        大小运行是2决定           大小编译时决定   
                        程序员分配                编译器分配
                        手动释放                  自动释放*/

    #include<stdio.h>
    #include<stdlib.h>
    int main(void)
    {
    int i=0,n;
    while(i++<100)
    {
    char *p;
    scanf("%d",&n);
    p=malloc(n+1);//在程序运行中可以随时调整空间的大小
    if(p == NULL)
    {
    perror("malloc");
    exit(-1);
    }
    scanf("%s",p);
    printf("%s ",p);
    free(p);            //一次开辟利用结束后立即释放,
    }
    return 0;
    }
    ******************************************************
    #include<stdio.h>
    #include<stdlib.h>
    int main(void)
    {
    int i=0,n;
    while(i++<100)
    {
    scanf("%d",&n);
    char *p;
    p= (char *)malloc(n*sizeof(char));
    if(!p)
    {
    perror("malloc");
    exit(-1);
    }
    scanf("%s",p);
    printf("%s ",p);
    free(p);
    }
    return 0;
    }
    ================================================
    #include<stdio.h>
    #include<stdlib.h>
    int main(void)
    {
    int i=0,n;
    while(i++<100)
    {
    char *p;            //此句和下一句调换位置则不能编译,,真心不懂
    scanf("%d",&n);
    p=(char *)malloc(n*sizeof(char));
    if(p==NULL)
    {
    perror("malloc");
    exit(-1);
    }
    scanf("%s",p);
    printf("%s ",p);
    free(p);
    }
    return 0;

    }


  • 相关阅读:
    Help document of CAD Build
    NSTableView 中 NSTextField无法输入
    NSScrollView 内容显示不正常问题
    Mac 中 NSTrackingArea 鼠标移动事件捕获
    java定时任务调度框架
    uboot: initramfs image to roofs, and rootfs to initramfs image
    jfrog CLI(command line interface)
    git submodule list/clone/update
    python run javascript in ubuntu
    git blame
  • 原文地址:https://www.cnblogs.com/riskyer/p/3279780.html
Copyright © 2011-2022 走看看