该程序从标准输入读取行。每行打印在标准输出上,并带有行号。该程序没有内置限制,可以处理多长时间。
我的答案是:
#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时发生溢出。
最佳答案
尝试这个:
#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);