C语言 为什么即使在 C 中分配给一个大的可变长度数组也有一个固定值 -1?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4269756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:11:20  来源:igfitidea点击:

Why does a large variable length array has a fixed value -1 even if assigned to in C?

carrays

提问by dubbeat

I'm trying to make a variable sized array in c.

我正在尝试在 c 中创建一个可变大小的数组。

The array keeps on coming back as having a value of -1.

数组不断返回,值为 -1。

What I want to do is to make an array of size sizeand then incrementally add values to it. What am I doing wrong?

我想要做的是制作一个大小的数组,size然后逐步向其中添加值。我究竟做错了什么?

int size = 4546548;

UInt32 ar[size];
//soundStructArray[audioFile].audioData = (UInt32 *)malloc(sizeof(UInt32) * totalFramesInFile);
//ar=(UInt32 *)malloc(sizeof(UInt32) * totalFramesInFile);
for (int b = 0; b < size; b++)
{
    UInt32 l = soundStructArray[audioFile].audioDataLeft[b];
    UInt32 r = soundStructArray[audioFile].audioDataRight[b];
    UInt32 t = l+r;
    ar[b] = t;
}

采纳答案by jer

What you need is a dynamic array. One that you can allocate an initial size, then use reallocto increase the size of it by some factor when appropriate.

你需要的是一个动态数组。您可以分配一个初始大小,然后realloc在适当的时候使用某个因素来增加它的大小。

I.e.,

IE,

UInt32* ar = malloc(sizeof(*ar) * totalFramesInFile);
/* Do your stuff here that uses it. Be sure to check if you have enough space
   to add to ar and if not, call grow_ar_to() defined below. */

Use this function to grow it:

使用这个函数来增长它:

UInt32* grow_ar_to(UInt32* ar, size_t new_bytes)
{
    UInt32* tmp = realloc(ar, new_bytes);
    if(tmp != NULL)
    {
        ar = tmp;
        return ar;
    }
    else
    {
        /* Do something with the error. */
    }
}

回答by Wyatt Anderson

You should probably allocate (and subsequently free) the array dynamically, like so:

您可能应该动态分配(并随后释放)数组,如下所示:

int *ar = malloc(sizeof(int) * size);
for (int b = 0; b < size; b++)
{
    ...
}

// do something with ar

free(ar);

回答by Hervé

if you make size a const int that should work. Also, if your array is inside a function and size is an argument of said function, that should work too.

如果你让 size 成为一个应该工作的 const int 。此外,如果您的数组在一个函数内并且 size 是所述函数的参数,那也应该有效。

回答by Argote

C does not allow a variable to be used when defining an array size, what you'd need to do is use malloc, this should give you an idea:

C 不允许在定义数组大小时使用变量,您需要做的是使用malloc,这应该给您一个想法:

UInt32* ar;
ar = (UInt32*) malloc(size * sizeof(UInt32));

Don't forget to free it up afterwards

之后不要忘记释放它