现在的位置: 首页 > 综合 > 正文

关于realloc的用法

2013年12月05日 ⁄ 综合 ⁄ 共 415字 ⁄ 字号 评论关闭

realloc是用来追加内存分配的,一段代码如下,仅供参考:

#include <stdio.h>
int main(void)
{
	int *p = NULL;
	int num = 0;
	int count = 0;
	int i = 0;
	printf("Please input numbers:\n");
	scanf("%d",&num);
	while(num != 0)
	{
		++ count;
		p = (int*)realloc(p,count*4);
		*(p + count - 1) = num;
		scanf("%d",&num);
	}
	for (;i < count; i ++)
	{
		printf("%d ",*(p+i));
	}
	getch();
	return 0;
}

上述代码中,可以无限制地输入整数值进行存储,效果大致相当于链表,但效率比链表要低。如果在执行p = (int*)realloc(p,count*4);之前,p已经被malloc过,那么当用realloc时,可以简写如下:realloc(p,count*4);

抱歉!评论已关闭.