46 lines
1.3 KiB
C
46 lines
1.3 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
int *input_score(int size)
|
||
|
{
|
||
|
int *arr = (int *)malloc(sizeof(int) * size);
|
||
|
memset(arr, 0, sizeof(int) * 5); // 将 scores 指向的内存清零0
|
||
|
for (int i = 0; i < size; i++)
|
||
|
{
|
||
|
printf("请输入第 %d 个学生的成绩: ", i + 1);
|
||
|
scanf("%d", arr + i);
|
||
|
}
|
||
|
return arr;
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
int *scores = input_score(5);
|
||
|
// scores = NULL 的判断是必须的,因为 malloc 分配内存失败时,会返回 NULL
|
||
|
if (scores == NULL)
|
||
|
{
|
||
|
printf("内存分配失败\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
for (int i = 0; i < 5; i++)
|
||
|
{
|
||
|
printf("%d ", *(scores + i));
|
||
|
}
|
||
|
printf("\n");
|
||
|
printf("R%p\n", scores);
|
||
|
free(scores); // 释放后,打印的前两个值是随机的,因为内存已经被释放了,但是后面的值还在,所以还能打印出来
|
||
|
// free(scores); // 重复释放内存,会报错;一个指针只能释放一次内存
|
||
|
printf("R%p\n", scores);
|
||
|
for (int i = 0; i < 10000000; i++)
|
||
|
;
|
||
|
for (int i = 0; i < 5; i++)
|
||
|
{
|
||
|
// 会报错,因为 scores 指向的内存已经被释放了
|
||
|
// free(scores + i); // 释放指针数组中的每一个元素 malloc 分配的内存
|
||
|
printf("%d ", *(scores + i));
|
||
|
}
|
||
|
printf("\n");
|
||
|
return 0;
|
||
|
}
|