简体   繁体   English

如何将 static 数组转换为 c 中的动态数组?

[英]How to convert static array to dynamic array in c?

Suppose say I have a static array假设我有一个 static 阵列

int a[10];

At some point the the program I want to insert 11th element.So it will throw error as Index out of range error.在某些时候,我想插入第 11 个元素的程序。所以它会抛出错误,因为 Index out of range 错误。

So I want to create dynamic array a[] .所以我想创建动态数组a[] without changing static array.无需更改 static 阵列。 And I want to take more input to array a[] during run time (means scalability).而且我想在运行时对数组a[]进行更多输入(意味着可伸缩性)。

Replace int a[10];替换int a[10]; with int *a = malloc(10 * sizeof(int)); with int *a = malloc(10 * sizeof(int)); . . When you want to expand it to 11 elements, do a = realloc(a, 11 * sizeof(int));当您想将其扩展为 11 个元素时,请执行a = realloc(a, 11 * sizeof(int)); . . If either of the previous two functions return null, then you ran out of memory and should treat it like the error that it is.如果前两个函数中的任何一个返回 null,那么你用完了 memory,应该像错误一样对待它。 Finally, where your original array would have gone out of scope, put free(a);最后,如果您的原始阵列会超出 scope,请放free(a); . .

I don't think you can increase array size statically in C.我认为您不能在 C 中静态增加数组大小。

When it comes to static - we cannot increase the size of an array dynamically since we will define its size explicitly at the time of declaration itself.对于 static - 我们不能动态增加数组的大小,因为我们将在声明时明确定义其大小。 However you can do it dynamically at runtime using the realloc() in stdlib.h header.但是,您可以在运行时使用 stdlib.h header 中的 realloc() 动态执行此操作。 but when you create an array dynamically using malloc().但是当您使用 malloc() 动态创建数组时。

The typical response in this situation is to allocate a new array of the larger size and copy over the existing elements from the old array, then free the old array.这种情况下的典型反应是分配一个更大尺寸的新数组并从旧数组中复制现有元素,然后释放旧数组。
There are some resources which may help you to understand this.有一些资源可以帮助您理解这一点。 here 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM