简体   繁体   English

为什么我不必使用指针?

[英]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. 我不用h使用指针就解决了这个问题,但是我的直觉告诉我那时我应该使用指针,而且我不了解如果不使用指针怎么解决这个问题。 I am a bit confused because I have not coded C for a while now. 我有点困惑,因为我已经有一段时间没有编码C了。 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. 假设vectorelementos字段是elemento的数组,那么您所做的就很好。 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. 进行交换时,它会复制elemento结构的每个字段。

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. 例如,假设您的结构是一个非常大的结构,具有1000个字节,并且其中有100个字节。 Your array elementos would then be 100,000 bytes of contiguous memory in 1000-byte chunks. 这样,您的数组elementos将是100,000字节的连续内存(以1000字节为块)。 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. 您的交换函数会将整个1000字节的结构复制到aux ,然后从数组的远端将1000字节复制到近端,然后将aux 1000字节复制到远端。 That's copying 3000 bytes per swap, 50 times. 每次交换复制3000字节,即50次。

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. 相反,如果elementos是指向100个结构的指针的数组(每个结构都使用malloc()分配到其他位置),则交换函数将仅移动24个字节50次,这些结构本身将保留在内存中,并且仅指向它们的指针会移动。 This is much more efficient, at the cost of the memory for the pointer array. 这要高效得多,但要消耗指针数组的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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