qfedu-c-level/day11/d6_3.c

36 lines
840 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memset
int main()
{
// 定义字符数组,接收用户输入的内容(最大值为 100 B
char *p = (char *)malloc(100 * sizeof(char));
if (NULL == p)
{
perror("malloc");
return 1;
}
memset(p, 0, 100 * sizeof(char));
printf("data: ");
scanf("%s", p);
// strlen() 获取字符的个数
int len = 0;
while (p[len++])
; // len = strlen(p);
if (len != 100)
{
printf("before realloc,%p\n", p);
// 重新分配空间
p = (char *)realloc(p, (len) * sizeof(char));
printf("after realloc,%p\n", p);
}
printf("%s, size of p: %d\n", p, len); // 重新分配空间后p 的大小不变
free(p); // 释放空间
return 0;
}