this is the slogan:
Write a function to add an element to the end of a vector. where v is the vector to add an element to, n is the maximum length of vector v, util is a pointer to the variable that stores the number of currently used elements of v, and elem is the element to add. The function should add elem to the end of the used elements of vector v, and increment the value of the variable pointed to by util by 1. The function should return zero if it was able to successfully add the element, and 1 in the case that vector v is full and the element cannot be added to the array.
and this what I did:
int agregar(int v[], int n, int* util, int elem){
// Programar la funcion aqui
for(n=0; n<*util; n++) {
v[n]=elem;
n=n+1;
return 0;
}
return 1;
}
my question is to know if the slogan is well raised and how to test my code with a vector?
To test the code you just have to call the function with the parameters it expects.
For that you need to create at least one array and one variable that keeps track of the elements it has.
Then you can print the variables and elements of the array to see if it's working as it should.
You can see how it works here .
The code has several bugs.
You should use
n
in conjunction with*util
to know if the vector has space. When using it as an iteration variable, its original content is lost.If you did not register any element,
*util
it should be 0. Therefore, the for does not even reach the first iteration and the element is not assigned. It will stay that way unless there is some external modification.Yes
*util > 0
, the for would be replacing all the elements with the one you want to add. But in the for there is a return. So you will only be able to iterate once at most. So why use a for when the code inside it will only be executed once?Suppose the element was added. But you are not increasing the variable that keeps track of the elements. So you will be writing the element always in the same place.
Fixing the problems and making the code a bit more readable, it would look something like this:
You can try it here .