动态内存是由程序员手动分配,不再使用时,一定记得释放内存。
静态内存是程序开始运行时由编译器分配的内存,它的分配是程序开始编译时完成的,不占用cpu资源。程序中的各种变量在编译源程序时就已经分配了内存空间,当该变量在作用域内使用完毕时,系统自动释放所占用的内存空间。问题是内存不足或溢出的问题。
编译器进行编译时,会对变量进行分配和释放,释放是由变量的作用域决定的,
#include "stdio.h"#include "stdlib.h"int main(){char *p;// 为指针p开辟一个内存空间p = (char *)malloc(100);if(p){printf("Memory Allocated at: %x\n",p);}else{printf("Not Enough Memory\n");}char ch;// 从控制台输入一个字符ch=getchar();// 调整p内存空间从100字节到ch个字节p = (char *)realloc(p,ch);if (p){printf("Memory Reallocated at: %x\n",p);}else{printf("Not Enough Memory!\n");}// 释放p所指向的内存空间free(p);return 0;}
更改字符串数组中的内容
#include "string.h"#include "stdio.h"int main(){char str[]="welcome to mrsoft\n";printf("s before memset%s\n",str);memset(str,'R',strlen(str)-1);printf("s after memset:%s\n",str);return 0;}