wall
This commit is contained in:
37
malloc.c
Normal file
37
malloc.c
Normal file
@ -0,0 +1,37 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <windows.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
SetConsoleOutputCP(65001); // 设置控制台为 UTF-8 编码,配合 #include <windows.h> ,终端输出的就不是乱码
|
||||
int* ptr;
|
||||
// 分配可以存储 5 个 int 值的内存块, 内存中的值是随机的
|
||||
ptr = (int*)malloc(5 * sizeof(int));
|
||||
if (ptr == NULL)
|
||||
{
|
||||
printf("内存分配失败\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// 使用分配的内存块
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
ptr[i] = i + 1;
|
||||
}
|
||||
|
||||
// 打印内存中的值
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
printf("%d ", ptr[i]);
|
||||
}
|
||||
printf("\n");
|
||||
// 释放内存
|
||||
free(ptr);
|
||||
|
||||
system("pause"); //保持终端存在,配合 #include<stdlib.h>
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user