Is it possible to extend a static array in C?
I tried creating a function which allocates a new dynamic array, copies contents to it and returns it's pointer; but It didn't work correctly, I'm getting debug error everytime.
I need to do something like this;
int a1[5] = { 1,2,5,4,1 };
extend(a1); //or a1* = extend(a1);
.
.
.
a1[9] = 2;
My extend function so far;
int extend(int x[], int oldSize, int newSize) {
int *extendedX = (int*)calloc(newSize, sizeof(int));
int i = 0;
for (; i < oldSize;i++) {
extendedX[i] = x[i];
}
for (; i < newSize; i++) {
extendedX[i] = 0;
}
return *extendedX;
}
You can't extend static array.
you can do it like this:
#include <stdio.h>
int *extends(int ar[],int oldsz,int newsz){
int *newAr = malloc(newsz*sizeof(int));
for(int i = 0; i < oldsz;i++){
newAr[i] = ar[i];
}
return newAr;
}
int main(void) {
int i,a[5] = { 1, 2, 3, 4, 5};
int *a1 = extends(a,5,10);
a1[5] = 6;
a1[6] = 7;
a1[7] = 8;
a1[8] = 9;
a1[9] = 10;
a1[10] = 11;
a1[11] = 12;
for(i = 0; i < 12; i++)printf("%d ",a1[i]);
return 0;
}