-1

我正在尝试制作一个单词计数器程序,并希望在没有额外空间的情况下为字符串动态分配内存。到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>

char *strmalloc(char *string);
char *user_input = NULL;

int main(void) {
    printf("Enter a sentence to find out the number of words: ");
    strmalloc(user_input);
    printf("You entered %s", user_input);
    return 0;
}

char *strmalloc(char *string) {
    char *tmp = NULL;
    size_t size = 0, index = 0;
    int ch;

    while ((ch = getchar()) != '\n' && ch != EOF) {
        if (size <= index) {
            size += 1;
            tmp = realloc(string, size);
            if (!tmp) {
                free(string);
                string = NULL;
                break;
            }
            string = tmp;
        }
        string[index++] = ch;
    }
    return string;
}

这是输出:

Enter a sentence to find out the number of words: Testing program
You entered (null)
Process finished with exit code 0

我认为在 while 循环中,我重新分配了 1 个字节的内存,直到字符串正好合适?我究竟做错了什么?

4

1 回答 1

1

在您的功能中:

char *strmalloc(char *string) {===>char *strmalloc(char **string) {

tmp = realloc(string, size);===>tmp = realloc(*string, size);

string = NULL;===>*string = NULL;

string = tmp;===> *string = tmp;

string[index++] = ch;===>(*string)[index++] = ch;

return string;===>return *string;

在调用函数中:

strmalloc(user_input);===>strmalloc(&user_input);

于 2021-01-09T17:06:53.993 回答