Call function to allocate vector in C

Asked

Viewed 61 times

0

Hello, I’m creating a program to call a function that should allocate a vector to be used in main(), but I’m having difficulty, I imagine I should use a pointer to pointer, but I don’t have much experience with it. What mistake would I make? The code is as follows::

#include <stdio.h>
#include <stdlib.h>
typedef struct pnt{
    int x;
    int y;
}ponto;
void cria_vetor(ponto** conjunto);
int main(){
    ponto* conjunto;
    ponto** ptrconj = &conjunto;
    void cria_vetor(ptrconj);// chamo a função para alocar o vetor
    int i;
    for(i = 0; i<5; i++){// imprimo os números do vetor
        printf("\n\tponto %d:\nx = %d\ty = %d", i, conjunto->x, conjunto->y);
    }
    return 0;
}
void cria_vetor(ponto** conjunto){
    *conjunto = (ponto*)malloc(5*sizeof(ponto)); // alocando o vetor
    int i;
    for(i=0; i<5; i++){//escrevo alguns números no vetor para testar
        (*conjunto)->x = i;
        (*conjunto)->y = 4-i;
    }
}
  • 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

  • You know you’ll need this, so the first function you write is one that shows the dots on a vector. "Defensive programming". :)

1 answer

1


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.