【发布时间】:2020-12-31 19:58:05
【问题描述】:
我的问题在另一个以前的旧问题中得到了回答,但只用代码回答,没有解释link。
我很想回答为什么那里的代码有效而我的无效(我错过了什么?),这是我的:
#include <stdio.h>
#include <stdlib.h>
void get_sentence(char* sentence) {
char end_of_input = 'a', * temp_pointer = NULL;
for (unsigned short int input_index = 0; end_of_input != '\n'; input_index -= -1) {
temp_pointer = sentence;
sentence[input_index] = end_of_input = getchar();
printf("%d: %c\n", (1 + input_index), end_of_input);
if (end_of_input == '\n') {
printf("end of input\n");
sentence[input_index] = '\0';
return;
}
sentence = (char*)realloc(sentence, ((int)(input_index + 2)) * sizeof(char));
if (sentence == NULL) {
free(temp_pointer);
return;
}
}
}
void main(int argc, char const* argv[]) {
char* sentence = malloc(sizeof(char));
if (sentence == NULL) {
printf("blyat");
exit(1);
}
get_sentence(sentence);
printf("Answer = ");
for (unsigned short int run = 0; sentence[run] != '\0'; run -= -1)
printf("%c", sentence[run]);
printf("\n");
free(sentence);
exit(0);
}
在答案代码中,他还写了+=16,这不是浪费内存吗?
【问题讨论】:
-
请注意,
get_sentence函数中的sentence变量是该函数的本地变量,对其进行的修改不会反映在main中。 -
更改函数内部的参数(如
sentence)不会更改函数外部的相应变量,即使该参数是指针(这是新手似乎感到困惑的一点) . -
@barakadax 对我来说,更简单的解决方案是从函数中返回(可能)句子的新值。
-
+= 16是速度和内存之间的权衡。是的,它浪费了一点内存,但这意味着您不需要为要添加到字符串中的每个字符调用相对昂贵的realloc。请注意,最后一个realloc放弃了任何额外内容,因此毕竟没有浪费内存。 -
@ikegami 由于所有
malloc()实现必须返回内存"suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement",实际上+=16不会浪费太多空间,因为在内部,堆内存是按块分配的。在 Linux 中,我很确定块大小为 16,因此在这种情况下,+=16实际上可能是最佳的,而用于修剪内存的最终realloc()实际上没有用。 (这也是为什么超出malloc()'d 缓冲区通常绝对零症状的原因。)