问题描述
我的问题在之前的另一个旧问题中得到了回答,但只用代码回答,没有解释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
,这很浪费内存不是吗?。
解决方法
它正在工作,谢谢“@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);
}