c - C得到未知的输入长度
问题描述
我的问题在这里的另一个以前的旧问题中得到了回答,但只用代码回答了,没有解释链接。
我想要一个答案,为什么那里的代码有效而我的无效(我错过了什么?),这是我的:
#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);
}
推荐阅读
- angular - 仅在构建中导入 Angular 材料时出错
- javascript - 加载jsp页面耗时过长
- documentum - 如何使用 Documentum 中的 DQL 获取文件柜中已删除的文档列表?
- github - 使用 Heroku 部署的 Jhipster 应用程序,但在连接到 github 构建后未触发
- javascript - 如何将数组中相邻的数字组合成单个数字并返回一个包含“5”、“6”、“7”、“8”、“9”、“10”、“11”的数组?
- amazon-web-services - AWS S3 选择获取名称中带有 / 的列的数据
- pandas - 未与 X 轴刻度对齐的条形和散景图中的第一个条形截止
- python - 使用 postgres/Python 选择撇号
- python - 我用python编写的程序有什么问题?
- ios - 当应用程序在 Swift 中处于后台或非活动状态时,如何搜索 BLE/蓝牙设备?