我正在用c语言编写一个有关动态数组的程序,代码是:
#include <stdio.h>
struct Vector {
int size;
int capacity;
int *arr;
};
void add(struct Vector *Arr, int data) {
if (Arr->size == Arr->capacity) {
Arr->capacity *= 2;
int arr[Arr->capacity];
//array copy
for (int i = 0; i < Arr->size; i++) {
arr[i] = Arr->arr[i];
}
Arr->arr = arr;
}
int size = Arr->size;
Arr->arr[size] = data;
Arr->size++;
}
void display(struct Vector *Arr) {
for (int i = 0; i < Arr->size; i++) {
printf("%d ", Arr->arr[i]);
}
printf("\n");
}
int main() {
int arr[10];
struct Vector
array = {0, 10, arr};
//fill the array
for (int i = 0; i < 10; i++) {
add(&array, i);
}
display(&array);
//more element than the init size
add(&array, 10);
display(&array); //where the error happened
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当数组增长时,它具有不同的输出,如下所示:
在gcc 4.9中使用dev-cpp:
在gcc8.2中使用vs代码
使用在线c编译器:
最后一个是我的期望。
问题是您的行为不确定,因此任何事情都可能发生。它可以在不同的机器或编译器上以不同的方式体现。考虑一下:
if (Arr->size == Arr->capacity) {
Arr->capacity *= 2;
int arr[Arr->capacity];
...
Arr->arr = arr; // Arr->arr points to a local variable!
Run Code Online (Sandbox Code Playgroud)
在这里,您要创建一个新数组,然后将其地址分配给向量。但是,当该功能完成时,该内存将变为无效。相反,将其替换为:
int *arr = malloc(sizeof(int) * Arr->capacity);
Run Code Online (Sandbox Code Playgroud)
您将获得以下输出:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
完成后不要忘记free它。为了得到那个正常工作,我将建议改变int arr[10];以int arr = malloc(10*sizeof(int));使阵列永远是在栈上,然后把free(Arr->arr);之前Arr->arr = arr;还有一个free(array.arr);在节目的结尾。