how can i define an array in c which works like vector? This array should take any amount of values. It can take 0 values or 10 values or 100 values.
The code below works but gives me a runtime error that stack was corrupted.
int i = 0;
int* aPtr = &i;
int* head = aPtr;
for(i=0;i<6;i++){
(*aPtr)=i;
aPtr++;
}
Similarly how can i use char* str to take any amount of characters followed by null character in end to make a string?
Practice for interviews 🙂
There are many ways to do this in C, depending on your requirements, but you said “any number of values” (which usually means as many as will fit in memory). That’s commonly done using
reallocto grow the size of an array dynamically. You’ll need to keep some bookkeeping information too on the size of the array as it grows.This being tagged “homework”, I’ve left some details to fill in such as the definition of vector_t.