+ 2
Foreach loop in C
hi guys, i'm trying to make a foreach loop in C, i wrote it two times (lines 6 and 9), but the first loop doesn't work correctly, if i decommented it, it gives me "no output". the second loop is the same of first's except i wrote a statement out of the loop, why only second one work well? which is the difference? https://code.sololearn.com/clMTythoeYwZ/?ref=app
5 ответов
+ 4
Or better yet:
for(p = ls; p < &ls[sizeof(ls)/sizeof(ls[0])]; p++) {
printf("%d\n", *p);
}
+ 5
p = ls;
for(int i = 0; i < sizeof(ls)/sizeof(ls[0]); p++, i++) {
printf("%d\n", *p);
}
+ 2
Hi, have you tried sizeof(ls)/sizeof(ls[0])? I tried your code seems incompatible with Playground, there was no output.
Hth, cmiiw
0
thank you for replying, yeah it was a very silly mistake (thanks @Gordie ), i didn't understand it before because the code playground gave me no error...🙈
@ChaoticDawg thanks for your solution, it is simpler than mine, i like it!
@Martin Taylor yeah i know it is not a foreach loop but i would like to create something similar :)
0
you're right @Gordie
i didn't know it was possible to point an array directly (p = ls), i thought i had to point each element separately