#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//函数栈空间释放后,函数内所有局部变量消失
char* print_stack() {
char c[] = "stack";
put(c);
return c;
}
//堆空间不会因函数执行结束而释放
char* print_malloc() {
char* p;
p = (char*)malloc(20);
strcpy(p, "malloc");
puts(p);
return p;
}
int main() {
char* p;
p = print_stack(); //栈空间随着函数执行结束而释放
puts(p);//打印异常,乱码
p = print_malloc();//堆空间不会因函数结束而释放,必须free
puts(p);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//malloc实现动态数组
int main() {
int i;//申请多大空间
scanf("%d", &i);
char* p;
p = (char*)malloc(i);//malloc申请空间,单位:字节,不进行强制类型转换会有警告
char c;
scanf("%c", &c);//去除缓冲区里边的\n
gets(p); //读缓冲区数据,\n结束
puts(p);
return 0;
}