c - 静态、堆栈和堆分配有何不同?

标签 c arrays static stack

我怎样才能声明这样一个数组:

int array[1000000];

作为静态数组、堆栈数组和堆分配数组?

最佳答案

您的任务似乎是在寻找这个:

// global variable; NOT on the stack. Exists in the data segment of the program
int globalvar[1000000];

void func()
{
    // local stack-variable. allocated on the stack on function entry
    //  unavailable outside this function scope.
    int stackvar[1000000];

    // allocated on the heap. the only stack space used in the
    //  space occupied by the pointer variable.
    int *heapvar = malloc(1000000 * sizeof(int));
    if (heapvar != NULL)
    {
        // use heap var

        // free heap var
        free(heapvar)
    }
}

或者也许是这样的:

void func()
{
    // static variable; NOT on the stack. Exists in a program data segment (usually)
    static int staticvar[1000000];
    
    // local stack-variable. allocated on the stack on function entry
    //  unavailable outside this function scope.
    int stackvar[1000000];

    // allocated on the heap. the only stack space used in the
    //  space occupied by the pointer variable.
    int *heapvar = malloc(1000000 * sizeof(int));
    if (heapvar != NULL)
    {
        // use heap var

        // free heap var
        free(heapvar)
    }
}

就其值(value)而言,除非您有一个 4 或 8 兆字节的保留调用堆栈(或更大),否则上面的函数可能会在输入时出错。对于如此大的尺寸,通常使用堆 (malloc()/free())。但这似乎不是您的任务(目前)的内容。

关于c - 静态、堆栈和堆分配有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419811/

相关文章:

c++ - LDAP 连接 ldap_sasl_bind_s 给出断言

arrays - swift - 如何检查数组是否第 n 次包含字符串?

java - 如何使用静态变量和线程提高 Java 性能?

java - 如何制作继承的静态对象

c - C 中的 SSL 密码帮助

c - 如何使用管道在线程之间发送数组?

java - Object类引用如何接收原始类型数组基地址?

python - numpy 数组中非唯一行的快速组合,映射到列(即快速数据透视表问题,没有 Pandas)

java - 静态字段不更新

c - 从 C 中的 MMAP 中删除空格