程序從標準輸入中讀取行。每行都打印在標準輸出之前的行號上。該程序對它可以處理的行數沒有限制。練習中的動態內存分配
我的回答是:
#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時,我有溢出。
你可以使用['getline'](http://man7.org/linux/man-pages/man3/getline.3.html)嗎?它會爲你做所有的單調乏味的工作。 – 5gon12eder 2014-10-11 00:21:15
http://stackoverflow.com/questions/4346598/gets-function-in-c永遠不會使用得到 – pm100 2014-10-11 00:24:04
其也不清楚你的想法。你是試圖將所有的行存儲在內存中,還是隻創建一個足夠大的緩衝區來存儲最大的緩衝區 – pm100 2014-10-11 00:25:44