# 如何声明可变大小的数组（全局）

18

Misterxp

22

1 /如何在数组外部声明数组的恒定大小？

``````#define ARRAY_SIZE 10
...
int myArray[ARRAY_SIZE];``````

``````const int ARRAY_SIZE = 10;
...
int myArray[ARRAY_SIZE];``````

``````int myArray[] = {1, 2, 3, 4, 5};
const int ARRAY_SIZE = sizeof(myArray) / sizeof(int);``````

2 /如何获得一个动态大小的数组（即直到运行时才知道）？

``````// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source)
if (myArray != 0) {
myArray = (int*) realloc(myArray, size * sizeof(int));
} else {
myArray = (int*) malloc(size * sizeof(int));
}``````

``````// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source or through other program logic)
if (myArray != 0) {
delete [] myArray;
}
myArray = new int [size];``````

4
1）`ARRAY_SIZE = sizeof myArray / sizeof myArray[0];`，这样您就可以更改myArray的类型而不会引入错误。由于相同的原因，`myArray = realloc(myArray, size * sizeof *myArray);`。顺便说一句，强制转换`malloc()`或的返回值`realloc()`也没有用。2）`myArray != 0`在C版本中检查无用，`realloc(NULL, sz)`等效于`malloc(sz)`

const int ARRAY_SIZE = 10; int myArray [ARRAY_SIZE]; 您真的认为有可能吗？这将使可变地修改阵列误差C.

CI中的@ArunCheriyan不知道，但是在C ++中，它可以编译并完美运行。由于Arduino基于C ++，因此这里没有问题。
jfpoilpret

0

``char *chararray = malloc(sizeof(char)*x);``

``````const int arrsize = 10;
char array1[arrsize];
int array2[arrsize];``````

JRobert

[有点题外话，但是“用户”是模棱两可的，因为它可能意味着许多人中的一个。如果没有另外说明，通常表示最终用户，即最终产品的消费者。可能是下一位程序员，您的代码的下一位消费者，实际上，在我忘记了代码的实质内容之后，实际上可能是（通常，以我自己的经验）一年或更长时间。或系统设计师将您的代码作为现成的模块包含在他/她的产品中。我怀疑您是第二个“用户”。
JRobert

0

0

``````int arrSize;
int myArray[arrSize];``````

``````//First you create a pointer for the memory space to be separated for the set you're creating
int* myArray;
int arrSize; //Then you define the variable that will determine the amount of elements the array is going to have, you can give it a value whenever you want as long as this int is defined before the values in myArray are set
myArray=(int*)calloc(arrSize,sizeof(int)) //Here, you establish that the instance myArray (whose memory space has already been separated through the creation of the pointer) will be separated into arrSize amount of elements of type int with a maximum memory value (in bytes) equal to the maximum available for the int type variables``````