Home > Software design >  What are the reasons or advantages to use &my_array[0] instead of my_array in assignments?
What are the reasons or advantages to use &my_array[0] instead of my_array in assignments?

Time:11-27

I'm seeing this kind of assignment:

info->table = &_ttable_full[0];

Why not directly use this:

info->table = _ttable_full;

Is there any advantage? Or is it just the author's style?

CodePudding user response:

In the use you show, there is no difference in C semantics.

In some circumstances, I would use A to indicate the resulting pointer may be used to access the entire array, whereas &A[0] suggests the pointer is intended for use only to access that specific element. Similarly, A j suggests the resulting address is the starting point for some algorithm, whereas &A[j] suggests that particular element is of interest. These are just to help the reader. Similar to using different typefaces in documents, they do not change the literal meaning of the text but help guide the reader in interpreting it.

Note there are some circumstances where A and &A[0] differ. sizeof A gives the size (number of bytes) of the array, whereas sizeof &A[0] gives the size of a pointer to an element of the array. &A gives a pointer to the array (which has a different type than a pointer to an element), whereas &&A[0] is not a normal part of the C grammar. (Some compilers may use && in an extension.)

CodePudding user response:

It's just a stylistic convention to make it clear you're providing an address to an array.

  •  Tags:  
  • c
  • Related