简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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