使用unsigned int size声明一个long long数组

时间:2020-12-27 02:29:59

I was doing a problem when I encountered a segmentation fault while declaring an array as:

当我在将数组声明为:1时遇到分段错误时,我遇到了问题:

long long ways[max+1];  

where,

哪里,

unsigned int max = findMax(l,T); // l is an unsigned int array and T is an int.  

and findMax is a function of the type:

和findMax是类型的函数:

unsigned int findMax(unsigned int arr[],int size)  

How can I resolve this?

我该如何解决这个问题?

1 个解决方案

#1


2  

A probable reason is that the array is too big for the stack.

可能的原因是阵列对于堆栈来说太大了。

Typical stack sizes as of now is 1-16 Mb (could be considerably less in an embedded system). If long long is 8 bytes it would mean that allocating one array of more than 125000 elements could be problematic. And you also want to leave room for other auto variables.

目前的典型堆栈大小为1-16 Mb(在嵌入式系统中可能相当少)。如果long long是8个字节,则意味着分配一个超过125000个元素的数组可能会有问题。而且你还想为其他自动变量留出空间。

Really big arrays should not be allocated on the stack.

不应该在堆栈上分配真正大的数组。

You could try allocating it in the heap instead:

您可以尝试在堆中分配它:

long long *ways = calloc(max+1, sizeof *ways);
if (ways == NULL) {
    // allocation failed!!
}
// Do stuff.
free(ways);

#1


2  

A probable reason is that the array is too big for the stack.

可能的原因是阵列对于堆栈来说太大了。

Typical stack sizes as of now is 1-16 Mb (could be considerably less in an embedded system). If long long is 8 bytes it would mean that allocating one array of more than 125000 elements could be problematic. And you also want to leave room for other auto variables.

目前的典型堆栈大小为1-16 Mb(在嵌入式系统中可能相当少)。如果long long是8个字节,则意味着分配一个超过125000个元素的数组可能会有问题。而且你还想为其他自动变量留出空间。

Really big arrays should not be allocated on the stack.

不应该在堆栈上分配真正大的数组。

You could try allocating it in the heap instead:

您可以尝试在堆中分配它:

long long *ways = calloc(max+1, sizeof *ways);
if (ways == NULL) {
    // allocation failed!!
}
// Do stuff.
free(ways);