游客 Signup | Login
中文 | En

1273 - C语言11.9

编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。

另外,需要编写一个函数free,将new函数所占用的空间释放。free(p)表示将p(地址)指向的单元以后的内存段释放。
要求用结构体实现。

Input

只有一个正整数n,表示需要分配n个字节的内存空间。保证n不超过10000。

Output

只有一个字符串,为“OK”。

Examples

Input

1024

Output

OK

Solution C

#include <stdio.h>
#include <stdlib.h>
struct string {
	char * content;
	int size;
};
int main() {
	struct string * new(int);
	void fre(struct string *);
	struct string * p;
	int n;
	scanf("%d", &n);
	p = new(n);
	fre(p);
	puts("OK");
	return 0;
}
/* new函数,为n个字符分配连续空间 */
struct string * new(int n) {
	/* 为结构体分配内存 */
	struct string * result = (struct string *)malloc(sizeof(struct string));
	/* 为字符串分配内存 */
	result->content = (char *)malloc(sizeof(char) * n);
	result->size = n;
	return result;
}
/* free函数,将p指向的内存空间释放 */
void fre(struct string * p) {
	int i;
	/* 将p->content指向的字符串空间释放 */
	free(p->content);
	/* 将p指向的结构体空间释放 */
	free(p);
}

Solution C++

#include<iostream>
using namespace std;

int main()
{

	int n;
	char *p;
	scanf("%d",&n);
	p=new char[n];
	delete p;
	printf("OK\n");

	return 0;
}
Time Limit 1 second
Memory Limit 32 MB
Discuss Stats
上一题 下一题