简体   繁体   中英

Why don't I have to use pointers?

On the exercise we have a vector of structures, and we need to invert the order of the vector. I have solved the problem without h using pointers, but my gut tells my I should have used then, and I'm not understanding how is it possible to solve this without using them. I am a bit confused because I have not coded C for a while now. I apologize for the variable/structures names not being in English, but they s are very close and understandable by any English speaking person.

typedef struct{
   char *str;    
} elemento;

typedef struct{
    int tamanho;
    int capacidade;
    elemento* elementos;   
} vetor;


void vetor_inverte(vetor *vec){

    elemento aux;
    int i=0;

    for(i=0; i<(vec->tamanho)/2; i++){
        aux = vec->elementos[i];
        vec->elementos[i] = vec->elementos[ vec->tamanho -1-i ];
        vec->elementos[ vec->tamanho -1-i ] = aux;
    }
}

Assuming that the elementos field of vector is an array of elemento , what you're doing is fine. You're swapping the first with the last, then the second with the second-to-last, and so forth.

When you do the swap, it does a copy of each field of the elemento struct.

I don't see a need to involve pointers in this case.

You're doing a lot more work than necessary, but it works.

Let's say, for example, that your structure were a really big one with 1000 bytes, and that you had 100 of them. Your array elementos would then be 100,000 bytes of contiguous memory in 1000-byte chunks. Your swap function would copy a whole 1000-byte structure to aux , then copy 1000 bytes from the far end of the array to the near end, then copy 1000 bytes of aux to the far end. That's copying 3000 bytes per swap, 50 times.

If instead elementos were an array of pointers to the 100 structures (each allocated elsewhere, with malloc() ), your swap function would only be moving 24 bytes 50 times, the structures themselves would stay put in memory and only the pointers to them would move. This is much more efficient, at the cost of the memory for the pointer array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM