[英]C getting unknown input length
我的问题在这里的另一个以前的旧问题中得到了回答,但只用代码回答了,没有解释链接。
我想要一个答案,为什么那里的代码有效而我的无效(我错过了什么?),这是我的:
#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
浪费了 memory 不是吗?
它正在工作,谢谢“@Johnny Mopp”♥。
#include <stdio.h>
#include <stdlib.h>
char* get_sentence() {
char end_of_input = 'a', *sentence = malloc(sizeof(char)), *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();
if (end_of_input == '\n') {
sentence[input_index] = '\0';
return sentence;
}
sentence = (char*)realloc(sentence, ((int)(input_index + 2)) * sizeof(char));
if (sentence == NULL) {
free(temp_pointer);
return NULL;
}
}
}
int main(int argc, char const* argv[]) {
char* sentence = get_sentence(&sentence);
if (!sentence)
exit(1);
printf("Answer: %s\n", sentence);
free(sentence);
exit(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.