【问题标题】:dynamic memory allocation using the stack not the heap in C使用堆栈而不是 C 中的堆进行动态内存分配
【发布时间】:2023-03-21 11:04:01
【问题描述】:

我编写了一个小代码来动态分配存储完整输入所需的内存大小,但使用带有 malloc 和 realloc 的堆

有什么办法可以只使用堆栈将完整的用户输入存储在内存中吗?

代码:

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

int main(int argc, char* argv[]){
    int c = 0;
    int buffer_length = 2;
    int buffer_pos = 0;
    char *buffer = (char *)malloc(buffer_length * sizeof(char));

    while(c != 10){
        c = getchar();

        if(buffer_pos >= buffer_length - 1){
            buffer_length += 2;
            buffer = realloc(buffer, buffer_length * sizeof(char));
        }

        buffer[buffer_pos] = c;
        buffer_pos++;
    }

    printf("%s",buffer);

    free(buffer);
    main(0,NULL);

}

【问题讨论】:

  • 你乘错了大小,应该是sizeof(char)
  • 为什么?我正在使用 char* 缓冲区,而不是 char 缓冲区
  • char * 是指向字符数组的指针,而不是指向字符指针的指针。

标签: c


【解决方案1】:

不,这在堆栈中是不可能的。

您可以使用可变长度数组来分配大小来自表达式的本地数组。但是一旦分配,就不能改变大小了。

如果你需要调整数组的大小,你必须使用malloc()realloc()的动态分配。

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2019-11-21
    • 2010-12-11
    • 2020-09-15
    • 2017-01-04
    • 2011-12-01
    • 2014-01-19
    • 1970-01-01
    相关资源
    最近更新 更多