2

Is there any different between the two:

for (int i=0; *(strings+i) != NULL ;i++)
    len_strings += strlen(*(strings+i));

And:

for (int i=0; strings[i] != NULL ;i++)
    len_strings += strlen(strings[i]);

Or is it more of a stylistic difference and there's no actual difference between the two in how it compiles/executes? Is one preferred over another for any particular cases or reasons?

1
  • 2
    The practical difference is that it is easier to type the subscript notation, and much, much easier to manage double subscripts than the alternative: ptrptr[i][j] vs *(*(ptrptr + i) + j). Use the subscript notation most of the time. Occasionally there's a benefit to using the alternative, but not often. Commented Sep 30, 2019 at 3:06

2 Answers 2

3

The C standard defines E1[E2] to be the same as (*((E1)+(E2))) for any expressions E1 and E2, so there is no semantic difference.

For most uses, the subscript notation is preferred and more readable, but the pointer notation may be useful when one wants to emphasize some particular aspect for readers.

Sign up to request clarification or add additional context in comments.

Comments

0

In practice, two variants are identical; the array notation will probably look more readable to most people.

However, using the pointer notation allows to rewrite the loop slightly, which might be a bit of (micro)optimization which any decent optimizing compiler could do anyway:

for (char** ptr = strings; ptr != NULL; ++ptr)
    len_strings += strlen(*ptr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.