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