What is the difference between these ways of indexing a pointer to an array of structs in c?

Asked

Viewed 398 times

4

Is there any difference in the use of these 3 statements?

void addCliente(struct cliente *dadosCliente){
    dadosCliente[k].nome="oi";
    (*(dadosCliente+k)).nome="oi";
    (dadosCliente+k)->nome="oi";
}
void main(){
    struct cliente clientes[1000];
    addCliente(clientes);
}
  • How is the structure used? nome is a pointer, right?

  • 4

    No difference except for the readability. All will have the same effect.

  • 2

    The question is cool, but it’s not exactly about "statement" (or even "attribution") of strings, but about ways to access elements of a struct, isn’t it? In this case, I suggest editing at least the title to make it clearer.

1 answer

15


The three ways to access a struct in an array are equivalent.

Therefore:

  • (*(a+b)).c is (a+b)->c
  • (*(a+b)).c is a[b].c
  • and would have some more efficient than other?

  • 2

    No. They are exactly the same semantically. Just different ways of saying the same thing.

  • 3

    @user2984406: Compilers nowadays are very good at optimizing code, often greatly changing its structure. Accessing an array through the index in a well-defined loop allows the compiler to do these optimizations more easily, and makes the code much more readable for those who will do the maintenance later.

Browser other questions tagged

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