任何人都可以向我解释为什么这不起作用?
#include <stdio.h>
#include <stdlib.h>
char *getline(int lim)
{
char c;
int i;
char *line;
line = malloc(sizeof(char) * lim);
i = 0;
while((c = getchar()) != '\n' && c != EOF && i < lim-1)
{
*line = c;
line++;
i++;
}
*line = '\0';
printf("%s", line);
return line;
}
Run Code Online (Sandbox Code Playgroud)
我现在并不担心返回价值 - 只是为什么printf("%s", line)
不起作用的原因.
谢谢!
编辑:修复line = malloc(sizeof(char) * lim);
但它仍然无法正常工作.
解决方案:*line
整个功能中的地址递增.传递给它时printf()
,*line
指向'\ 0',因为它的地址增加到了.使用存储由malloc()
to 分配的原始地址*line
然后将该指针传入的temprorary指针printf()
,允许该函数向上走指针.
因为您只为此行中的单个字符分配了足够的空间:
line = malloc(sizeof(char));
Run Code Online (Sandbox Code Playgroud)
\0
在你的printf
陈述之前,这已经充满了.
我猜你要改变这一行:
/* Allocate enough room for 'lim' - 1 characters and a trailing \0 */
line = malloc(sizeof(char) * lim);
Run Code Online (Sandbox Code Playgroud)
甚至更好:
char *line, *tmp;
tmp = line = malloc(sizeof(char) * lim);
Run Code Online (Sandbox Code Playgroud)
然后tmp
在所有指针数学中使用,这种方式line
仍将指向字符串的开头.
我知道这是你开发的早期阶段,但你要确保你free()
的记忆malloc()
.
这是您的函数的工作版本,包括我建议的更改:
#include <stdio.h>
#include <stdlib.h>
char *getline(int lim)
{
char c;
int i;
char *line, *tmp;
tmp = line = malloc(sizeof(char) * lim);
i = 0;
/* NOTE: 'i' is completely redundant as you can use 'tmp',
* 'line,' and 'lim' to determine if you are going to
* overflow your buffer */
while((c = getchar()) != '\n' && c != EOF && i < lim-1)
{
*tmp = c;
tmp++;
i++;
}
*tmp = '\0';
printf("%s", line);
return line;
}
Run Code Online (Sandbox Code Playgroud)