當前位置:編程學習大全網 - 網站源碼 - 編寫壹個linux C語言程序 接受輸入壹個任意長度的字符串並輸出(使用malloc和realloc函數)

編寫壹個linux C語言程序 接受輸入壹個任意長度的字符串並輸出(使用malloc和realloc函數)

#include?<stdio.h>

#include?<stdlib.h>

#define?CHUNKSIZE?100

int?main()

{

char?*string;

int?i=0,c;

string=malloc(sizeof(char)*CHUNKSIZE+1);

if(string==NULL)

{

printf("out?of?memory");

return?1;

}

while((c=getchar())!=EOF)

{

string[i]=c;

i++;

if(i%CHUNKSIZE==0)

{

string=realloc(string,sizeof(char)*CHUNKSIZE*(i/CHUNKSIZE+1)+1);

if(string==NULL)

{

printf("out?of?memory");

return?1;

}

}

}

printf("\n\norgin?string?is:\n%s\n",string);

free(string);

return?0;

}

輸入任意長度字符串,CTRL+D結束輸入

  • 上一篇:Android系統源代碼多大?
  • 下一篇:選擇監控系統的保護罩需要註意哪些方面?
  • copyright 2024編程學習大全網