微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C 获取未知的输入长度

如何解决C 获取未知的输入长度

我的问题在之前的另一个旧问题中得到了回答,但只用代码回答,没有解释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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。