指针与动态内存申请

指针与动态内存申请:

数组长度固定是因为在栈空间中大小是确定的,要使用的空间大小不确定,就需要使用堆空间。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
int size;  //size代表要申请多大字节的空间
char *p;   //void类型的指针不能偏移
scanf("%d",&size);//输入要申请的空间大小
  //malloc返回的void*代表无类型指针
p=(char*)malloc(size);
strcpy(p,"malloc success");
puts(p);
free(p);   //释放申请的空间,释放的地址必须是malloc返回的地址
printf("free success");
return 0;
}
posted @ 2023-01-14 20:32  ntu202043  阅读(52)  评论(0)    收藏  举报