You have correctly reserved the amount of memory you wanted, but are accessing the same memory region always in the functions cria_vetor
and main
:
cria_vetor
:
(*conjunto)->x...
(*conjunto)->y...
main
:
conjunto->x...
conjunto->y...
The right thing would be increment the value of the memory that is in the referenced pointer and go to the next item of its vector:
(*conjunto + i)->x...
(*conjunto + i)->y...
and in function main
:
(conjunto + i)->x...
(conjunto + i)->y...
Understand the above code as if we were incrementing an index of a vector in a higher level programming language (conjunto[i]
). Remember that you do not have a vector properly in hand, and yes the memory address of the first vector item, i.e., a pointer. If we increment this memory value after you have allocated enough memory for the amount we wanted (as you did correctly at the beginning of the function cria_vetor
), we will always go to the next item from the current because that region has already been reserved for us.
Also remembering that you will receive an error from your program at runtime if you try to access a value above what you asked for in the initial memory allocation, such as accessing index 5 (five) of your array and only going up to 4 (four).
For the final result of the code, we would have something like:
#include <stdio.h>
#include <stdlib.h>
typedef struct pnt {
int x;
int y;
} ponto;
void cria_vetor(ponto** conjunto);
int main() {
ponto* conjunto;
cria_vetor(&conjunto);
for (int i = 0; i < 5; i++) {
// voltando a acessar os indices que desejamos
printf("ponto %d:\nx = %d\ty = %d\n", i, (conjunto + i)->x, (conjunto + i)->y);
}
// lembre-se de liberar toda a memoria heap que usar
free(conjunto);
return 0;
}
void cria_vetor(ponto** conjunto) {
// apontando para o primeiro item e alocando memoria suficiente para cinco
*conjunto = (ponto*)malloc(5 * sizeof(ponto));
for (int i = 0; i < 5; i++) {
// acessando os indices que desejamos
(*conjunto + i)->x = i;
(*conjunto + i)->y = 4 - i;
}
}
And the exit:
ponto 0:
x = 0 y = 4
ponto 1:
x = 1 y = 3
ponto 2:
x = 2 y = 2
ponto 3:
x = 3 y = 1
ponto 4:
x = 4 y = 0
I hope I’ve helped in some way.
There are many ways to do this, but possibly the simplest is to use what is called Factory Function, declaring
Ponto* cria_vetor(unsigned tamanho)
for example. And the most expressive and easy to use would be to declare a Set struct containing a vector with a certain number of points, because that’s what it’s doing. Let me know if you think you need a full example– arfneto
You know you’ll need this, so the first function you write is one that shows the dots on a vector. "Defensive programming". :)
– arfneto