我想知道在 C 中是否可以用另一个数组覆盖一个数组的内容,这样做后,我该如何解决数组大小丢失的问题?
假设我有两个数组。
int a[] = {1,2,3,4,6,7,8};
int b[] = {1,6};
// How can I overwrite the array a with array b, so get the following?:
a[] = {1,6};
最佳答案
当您声明一个像 a[] = {...} 这样的数组时,该数组将获得一个无法更改的固定大小,该大小在编译时确定。
如果你想使用动态数组,你需要在堆上分配,在 C 中这是通过 malloc 和 realloc 完成的。 realloc 允许您调整数组的大小。
例如
char* p = malloc(10);
char* q = realloc(p, 5); // now you made the array 5 bytes shorter
需要检查realloc的返回值才能知道realloc是否成功。
char* q = realloc(p, 5);
if (q != NULL) // successful
关于c - C语言中如何用另一个数组覆盖一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229102/