I am code a program about dynamic array in c language, the code is :
#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;
}
When the array growth, it has defferent output like below:
using dev-cpp with gcc 4.9:
using vs code with gcc8.2
using the online c compiler:
And the last one is my expectation.