回 帖 发 新 帖 刷新版面

主题:c语言大神可以帮忙 讲解一下这篇代码的每一步是什么意思吗?????~

#include <stdio.h>
#include <stdlib.h>

// Our new variable-length prompt function...but it doesn't
// quite work.  Try and identify and fix the problem.
char *prompt(char *mesg)
{
   int cur_array_len = 2;
   int pos = 0;
   char ch;
   char *text = NULL;
   printf("%s", mesg);
   // FIX: the initial malloc needs to be outside the array, otherwise
   // it interferes with the expanding part of the loop.
   text = malloc(sizeof(char) * cur_array_len);
   do
   {
      scanf("%c", &ch);
      if(ch == '\n')
      {
	 text[pos] = '\0';
      }
      else
      {
	 text[pos] = ch;
	 pos++;
	 if(pos == cur_array_len - 1)
	 {
	    // expand array
	    char *t2 = malloc(sizeof(char) * cur_array_len * 2);
	    int i;
	    for(i = 0; i < cur_array_len; i++)
	    {
	       t2[i] = text[i];
	    }
	    cur_array_len *= 2;
	    free(text);
	    text = t2;
	 }
      }
   } while(ch != '\n');
   return text;
}

// The original, fixed-size prompt function for reference.
char *org_prompt(char *mesg, int max_length)
{
   char *text = malloc(sizeof(char) * max_length);
   printf("%s", mesg);
   scanf("%s", text);
   return text;
}

int main(int argc, char *argv[])
{
   char *name = prompt("Enter name: ");
   printf("Hello %s, how are you?\n", name);
   free(name);
}

回复列表 (共1个回复)

沙发

C语言程序设计最新视频教程(2016)
C语言特训班内部视频,坚持30天,您就是C语言高手
高清完整版本百度网盘下载地址:
http://pan.baidu.com/s/1mhgTrrM
http://yun.baidu.com/share/link?shareid=921555821&uk=948035159
备注:赶紧下载,以备后用,以免链接失效
C语言程序设计交流QQ群(5140-31772)

我来回复

您尚未登录,请登录后再回复。点此登录或注册