1
我有这个代码示例,并且大致了解它的逻辑,但是我陷入了一些细节。C中的malloc - 返回值
#define LSH_RL_BUFSIZE 1024
char *lsh_read_line(void) {
int bufsize = LSH_RL_BUFSIZE;
int position = 0;
char *buffer = malloc(sizeof(char) * bufsize);
int c;
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
while (1) {
// Read a character
c = getchar();
// If we hit EOF, replace it with a null character and return.
if (c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
} else {
buffer[position] = c;
}
position++;
// If we have exceeded the buffer, reallocate.
if (position >= bufsize) {
bufsize += LSH_RL_BUFSIZE;
buffer = realloc(buffer, bufsize);
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
}
}
我不明白两件事:首先,这条线究竟干什么?
char *buffer = malloc(sizeof(char) * bufsize)
其次,以下线路如何工作?它是如何返回指针的?
return buffer;
“我们怎样才能返回一个指针?”只要用你可以返回一个整数的方式。你有什么理由认为你不能这样做? – MikeCAT
['malloc'](https://linux.die.net/man/3/malloc)向操作系统请求由其参数指定的内存块(在本例中为'bufsize')。你返回一个指针,就像你从函数中得到的任何其他值一样,其细节取决于[ABI](https://en.wikipedia.org/wiki/Application_binary_interface) – yano
我的意思是,它给了我们什么样的实用性在这个例子中? – AdamSMith