这是完全可能的,也很常见.适合工作的工具就是malloc()功能.这允许您在运行时动态创建任何大小的数组.一个示例是在运行时使用用户指定的大小创建数组.
int main(int argc, const char **argv)
{
printf("How long should the dynamic array be?");
int length;
scanf("%d", &length);
// dynamically create the array with malloc
int *array = malloc(sizeof(*array) * length);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个数组(指向int)可以像任何其他数组一样使用,通过[]运算符访问它的值.
int fifthValue = array[4]; // assumes array was malloc()'d with at least 5 mem slots.
Run Code Online (Sandbox Code Playgroud)
完成使用此动态创建的数组后,使用该free()函数将其内存返回给程序.
free(arr);
Run Code Online (Sandbox Code Playgroud)
第二种替代方法malloc()是calloc()功能.因为返回的内存块malloc()并不总是初始化,所以它可能包含垃圾数据.如果不希望这样,calloc()可以使用该功能.calloc()将为您初始化返回的内存的所有元素0.呼叫与呼叫calloc()略有不同malloc().
int main(int argc, const char **argv)
{
printf("How long should the dynamic array be?");
int length;
scanf("%d", &length);
// dynamically create the array with calloc and initialize it to 0
int *array = calloc(length, sizeof(*array));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
总之,这些malloc()和free()函数非常适合创建动态数组C.请记住始终free()使用malloc()(或calloc())保留的内存.