我如何在C中动态分配内存

How do I dynamically allocate memory in C

我正在尝试制作一个单词计数器程序,并希望为字符串动态分配内存而无需额外 space。到目前为止,这是我的代码:

#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个字节的内存,直到字符串正好合适?我做错了什么?

在你的函数中:

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);