(1)编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。
(2)写一函数free,将前面用new函数占用的空间释放。free(p)表示将p(地址)指向的单元以后的内存段释放。
#include <stdio.h>
#include <stdlib.h>
char *new(int n) {
char *p = (char *)malloc(n * sizeof(char));
return p;
}
void freeMemory(char *p) {
free(p);
}
int main() {
int n;
printf("Enter number of characters: ");
scanf("%d", &n);
char *str = new(n);
if (str == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
freeMemory(str);
return 0;
}
代码解释:
new
函数分配n个字符的连续内存空间。freeMemory
函数释放之前分配的内存。main
函数中,用户输入字符数,分配内存并输入字符串,最后释放内存。