I am new to C and had a question about dynamic arrays.
I am building a game so that when the user enters 6 numbers so that it matches the 6 random numbers that the code generates, the user wins.
I am trying to create a dynamic array to store the user's guesses until the user gets the answer correctly. However, I am unsure of how that would work. Would I create a function so that whenever the user gets an answer wrong, I call the function to create a new dynamic array to store the user's guesses?
What does a "vector" that can dynamically grow need to keep track of?
One that can store
intvalues.When you want to allocate a vector you can use
mallocto allocate the vector struct, but also the array that thedatamember will point to.When you want a vector to grow it's best to do this by a factor other than +1. For simplicity, let's use x2. You'd use
reallocto accomplish this, but in casereallocfails, we use a pointer other thanvec->datato test it so we don't leave the original pointer dangling. Once we know it succeeded we can assign it tovec->data.Remember on freeing such a structure you need to free the internal array as well. Two
malloccalls were made to bring this struct into existence, so twofreecalls are needed to destroy it.If we wanted to write a
push_onto_int_vecfunction, it might look like the following. A return value ofNULLindicating that the element was not added, otherwise returning the vector.