簡體   English   中英

具有malloc和realloc的C中的動態字符串數組不會退出循環

[英]Dynamic string array in C with malloc and realloc won't exit a loop

我一直試圖用C創建一個簡單的控制台應用程序(使用dev-c ++),該應用程序讀取字符並將它們放置在數組中,同時動態地加長數組以適應所需的任意數量的字符,直到按Enter。 代碼是這樣的:

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

main()
{
   int x=0;
   char * ch1;
   ch1 = (char*) malloc(1);

   do
   {
      ch1[x] = getche();
      x++;
      ch1 = (char*) realloc (ch1,x);
   } while (ch1[x-1]!='\n');

   printf("Input Sentence  Is :%s",ch1);
   free(ch1);
}

盡管程序可以正常運行且沒有錯誤,但是在鍵入句子並按Enter鍵而不是簡單地打印句子之后,“光標”將移回到窗口的開頭,您可以繼續在前面的字符上方鍵入內容。

編輯:我知道這不是一種最佳方法,因為您失去了退格功能,例如,我只是想看看它在我們今天教了malloc和realloc之后是否可以工作。

我可以肯定,這就是您要嘗試做的。 它和您的代碼之間的區別應該很明顯:

  • 使用calloc()作為初始緩沖區以確保其終止,
  • 檢查輸入流EOF以及CR和LF字符。
  • x表示緩沖區長度,而不是字符串長度。
  • 字符串終止是在每次成功擴展時建立的。
  • 解決了內存分配失敗。
  • 符合標准的main()聲明,
  • 使用符合標准的getchar()進行輸入。

碼:

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

int main()
{
    char *ch1 = calloc(1,1), *tmp;
    size_t x = 1;
    int c;

    if (!ch1)
    {
        perror("Failed to allocate string buffer.");
        exit(EXIT_FAILURE);
    }

    while ((c = getchar()) != EOF && c != '\r' && c != '\n')
    {
        tmp = realloc(ch1, x+1);
        if (!tmp)
        {
            // note: the string at ch1 still valid.
            perror("Failed to resize string buffer.");
            break;
        }

        ch1 = tmp;
        ch1[x - 1] = c;
        ch1[x++] = 0;
    }

    printf("Input Sentence: %s\n", ch1);
    free(ch1);

    return 0;
}

希望能幫助到你。

在當前系統(SUSE SLES-11)上,由於conio.h不可移植,因此無法編譯。 這是我的解決方案;

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

int main()
   {
   int     rCode   = 0;
   char   *buf     = NULL;
   size_t  bufSize = 0;
   int     done    = 0;

   /* Allocate a single byte to hold a string-termination 
    * character '\0' 
    */
   errno=0;
   buf = malloc(bufSize + 1);
   if(NULL == buf)
      {
      rCode=errno?errno:ENOMEM;
      fprintf(stderr, "malloc() failed. errno=%d\n", errno);
      goto CLEANUP;
      }
   ++bufSize;
   buf[0] = '\0';

   /** Loop until done. **/
   while(!done)
      {
      char *tmp;          /* Used to safely realloc(). */
      int ch = getche();  /* read the next character. */
      switch(ch)
         {
         case '\r':       /* Check for end-of-line characters. */
         case '\n':       /*  (I agree with Paul Z's comment. */
            done = (-1);  /* TRUE */

            /* Do not include these characters in the final buffer. */
            continue;     

         default:
            /* Change the last character of the buf from '\0' to ch. */
            buf[bufSize] = ch;  

            /* Increase the size of buf so that a new '\0' character can
             * be appended. 
             */
            errno=0;
            tmp=realloc(buf, bufSize+1);
            if(NULL == tmp)
               {
               rCode=errno?errno:ENOMEM;
               fprintf(stderr, "realloc() failed.  errno:%d\n", errno);
               goto CLEANUP;
               }
            buf=tmp;         // EDIT (Thanks Floris for catching this!)
            buf[bufSize++] = '\0';
            break;
         }
      }

   printf("Input Sentence Is: %s\n", buf);

CLEANUP:

   if(buf)
      free(buf);

   return(rCode);
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM