简体   繁体   English

如何在 C 中动态分配 memory

[英]How do I dynamically allocate memory in C

I'm trying to make a word counter program and want to dynamically allocate memory for the string without extra space.我正在尝试制作一个字计数器程序,并希望为没有额外空间的字符串动态分配 memory。 Here's my code so far:到目前为止,这是我的代码:

#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;
}

Here's the output:这是 output:

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

I thought that in the while loop, I reallocate 1 byte of memory until the string fits just right?我以为在 while 循环中,我重新分配了 memory 的 1 个字节,直到字符串正好合适? What am I doing wrong?我究竟做错了什么?

In your functiuon:在您的功能中:

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

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

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

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

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

return string; ===> return *string; ===> return *string;

In the calling function:在调用 function 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM