#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/************************************************************************/
/* 直接返回地址. */
/* */
/* */
/************************************************************************/
char* getLine(void)
{
const size_t sizeIncrement = 10;
char *buffer = (char*)malloc(sizeIncrement);
char *currentPosition = buffer;
size_t maximunLength = sizeIncrement;
size_t length = 0;
int character;
// malloc memory for buffer faile;
if (NULL == buffer)
{
return NULL;
}
while (1)
{
character = fgetc(stdin);
// \n is end input;
if (character == '\n')
{
break;
}
if (++length > sizeIncrement)
{
char *newBuffer = (char*)realloc(buffer, maximunLength += sizeIncrement);
if (NULL == newBuffer)
{
free(buffer);
return NULL;
}
// adjust currentPosition;
currentPosition = newBuffer + (currentPosition - buffer);
buffer = newBuffer;
}
*currentPosition++ = character;
}
*currentPosition = '\0';
return buffer;
}
/************************************************************************/
/* 返回的是输入的长度 */
/* */
/************************************************************************/
size_t getLinePoint(char **buffer)
{
const size_t sizeIncrement = 2;
// 保留原始的地址,用于指针的计算 。
char *pos = NULL;
// 用于实时调整指针的位置.
char *currentPosition = NULL;
*buffer = pos = currentPosition = (char*)malloc(sizeIncrement);
size_t maximunLength = sizeIncrement;
size_t length = 0;
int character;
// malloc memory for buffer faile;
if (NULL == buffer)
{
return 0;
}
while (1)
{
character = fgetc(stdin);
// \n is end input;
if (character == '\n')
{
break;
}
if (++length > sizeIncrement)
{
char *newBuffer = (char*)realloc(*buffer, maximunLength += sizeIncrement);
if (NULL == newBuffer)
{
free(buffer);
return 0;
}
// adjust currentPosition; 现在的位置 - 起点位置 = 已占用的空间.
// 新的起点 + 已占用空间的大小 = 新的浮动位置.
currentPosition = newBuffer + (currentPosition - pos);
// 重新调整地址.
*buffer = newBuffer;
}
*currentPosition++ = character;
}
// 程序最关键的地方. 否则会出现访问到其他地址内的数据.
*currentPosition = '\0';
return length;
}
int main()
{
char* a = NULL;
size_t b = 0;
//a = getLine();
//printf("stdin is %s", a);
b = getLinePoint(&a);
if (b > 0)
{
printf("stdin is %s", a);
}
return 0;
}
C realloc 实战
猜你喜欢
转载自my.oschina.net/u/1579560/blog/1819083
今日推荐
周排行