2014-10-11 66 views
0

程序從標準輸入中讀取行。每行都打印在標準輸出之前的行號上。該程序對它可以處理的行數沒有限制。練習中的動態內存分配

我的回答是:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAXSIZE 30 

int main(){ 

int line_n=0; 
char line[MAXSIZE]; 
char *p; 

while(gets(&line)) 
{ 
    if('\n'){ 
    if(*line=='q') break; 
    else if(strlen(line)>MAXSIZE){ 
    p=&line; 
    p=(char *)malloc(sizeof(strlen(line))); //failed to use dynamic memory allocation here 
     printf("%d).",line_n); 
     printf("%s\n",line); 
     } 
    else{ 
    printf("%d).",line_n); 
    printf("%s\n",line); 
    } 
} 
    line_n++; 
} 

我是相當新的C語言編程,我需要這方面的動態內存分配的幫助。當我的輸入大於MAXSIZE時,我有溢出。

+1

你可以使用['getline'](http://man7.org/linux/man-pages/man3/getline.3.html)嗎?它會爲你做所有的單調乏味的工作。 – 5gon12eder 2014-10-11 00:21:15

+0

http://stackoverflow.com/questions/4346598/gets-function-in-c永遠不會使用得到 – pm100 2014-10-11 00:24:04

+0

其也不清楚你的想法。你是試圖將所有的行存儲在內存中,還是隻創建一個足夠大的緩衝區來存儲最大的緩衝區 – pm100 2014-10-11 00:25:44

回答

1

試試這個:

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

#define ALLOCSIZE 30 

int main() 
{ 
    int line_n = 0; 
    char *line = NULL; 
    int linelen = 0; 
    int linecap = 0; 
    char *p; 
    int c; 

    while ((c = fgetc(stdin)) != EOF) 
    { 
     if (c == '\n') 
     { 
      if ((line) && (*line == 'q')) 
      { 
       linelen = 0; 
       break; 
      } 

      printf("%d).%.*s\n", line_n, linelen, line); 
      linelen = 0; 
      line_n++; 
     } 
     else 
     { 
      if (linelen == linecap) 
      { 
       p = (char *) realloc(line, linecap + ALLOCSIZE); 
       if (!p) break; 
       line = p; 
       linecap += ALLOCSIZE; 
      } 

      line[linelen] = c; 
      linelen++; 
     } 
    } 

    if (linelen > 0) 
     printf("%d).%.*s\n", line_n, linelen, line); 

    free(line); 

還是這個:

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

int main() 
{ 
    int line_n = 0; 
    char *line = NULL; 
    size_t linelen = 0; 
    char *p; 

    while (getline(&line, &linelen, stdin) != -1) 
    { 
     if (*line == 'q') break; 
     printf("%d).%.*s\n", line_n, linelen, line); 
     line_n++; 
    } 

    free(line); 
+0

我無法理解第一個解決方案中的這個聲明是什麼檢查以及它是如何檢查的:「if(!line)」,請你解釋這個聲明嗎? – 2014-10-11 00:52:22

+0

'if(!line)'檢查'line'是否爲NULL。 – 2014-10-11 17:43:11

0

如果你不wnat使用函數getline - 即你想要做繁重作爲鍛鍊; Tibial,那麼你必須要做到這一點

make a buffer (say 50 chars) with malloc 
loop 
    get 1 char 
    end of line? -> done 
    buffer full ? 
     use realloc to make bigger buffer 
    put 1 char in buffer 
+0

爲什麼我需要在開始的時候使用malloc如果我仍然不知道如果我以後需要它或者不需要它?這就像無內存地使用內存,不是? – 2014-10-11 00:38:55

+0

您不需要,您可以在第一次需要插入字符時分配它。 – 2014-10-11 00:46:00

+0

這基本上是如何在C++中的'vector'工作。每次閱讀新角色時,只能給自己多一個角色,但通過大塊地完成,你會獲得更好的性能,當然可能會浪費一些內存。 – IllusiveBrian 2014-10-11 00:46:58