Apparently your verificaCodigo
is on the whole, on the right path. There are some problems with your code as a whole that I have seen passing by:
- I do not understand why the two parameters need to be passed as pointers, I believe that it is a mistake, if there are no more errors because this way you are accessing the address of the memory and not the data you want (hence it may be getting dirt) .
- I do not know what
break
is doing there, it certainly can not exist. A break
out of a if
is usually not useful at all.
- Why is there a memory allocation in a function that only checks something? Either it checks something or it creates the new element (if that was the intention). Making the allocation in one place and leaving the fill in another exacerbates the clutter.
- If memory allocation error occurs, the return is 0 which is the same return if it does not find an equal (duplication) code, this does not make sense.
- Apparently you know how many renters are registered, this is what you get in
contador
. If this is the same, why calculate the totalLocatarios
that is not even being used?
- There are apparently other errors in using pointers for past information, since you're getting dirt in your memory.
- There are some problems where your code would not be trusted but I think it's not relevant to anyone learning.
- It is not a problem but I do not like the names of the variables you use, they do not indicate well what you are serving, you indicate one thing and you do another. You call your type the
Locatarios
structure but it only fits a lessee. The pointer to the array does make sense in the plural.
- As it's just an exercise I will not even mention problem saving a monetary value in
float
.
Probably the simplest solution for what you want is to reallocations from pLocatarios
every time to add a new element. It may not be very efficient but it does. And so your duplicity verification function will make sense. It would look something like this:
pLocatarios = realloc(pLocatarios, (sizeof(pLocatarios) / sizeof(pLocatarios[0]) + 1) * sizeof(pLocatarios[0]);
This is taking the amount of elements in the array , adding 1 and allocating this amount times the size of each element. You will need to make this operation anate to add a new renter.
If you keep the amount of renters saved somewhere is a bit easier, perhaps:
pLocatarios = realloc(pLocatarios, (totalLocatarios + 1) * sizeof(Locatarios);
This allocation should be done where you will add data from the new renter. In practice it is possible to create a code with only realloc
since if the initial pointer is NULL
it acts exactly equal to malloc
.
Maybe not too inefficient already that the operating system may, in some cases, make allocation optimizations that will prevent data copying. Anyway for an exercise it does not matter.