user12050586
user12050586

Reputation:

Practical difference between using array and pointer offset notation

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?

Upvotes: 2

Views: 1000

Answers (2)

IMil
IMil

Reputation: 1400

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);

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222689

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.

Upvotes: 3

Related Questions