+ 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

25th Sep 2017, 5:34 AM
Daniele
Daniele - avatar
5 Respuestas
+ 4
Or better yet: for(p = ls; p < &ls[sizeof(ls)/sizeof(ls[0])]; p++) { printf("%d\n", *p); }
25th Sep 2017, 7:05 AM
ChaoticDawg
ChaoticDawg - avatar
+ 5
p = ls; for(int i = 0; i < sizeof(ls)/sizeof(ls[0]); p++, i++) { printf("%d\n", *p); }
25th Sep 2017, 6:26 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Hi, have you tried sizeof(ls)/sizeof(ls[0])? I tried your code seems incompatible with Playground, there was no output. Hth, cmiiw
25th Sep 2017, 6:11 AM
Ipang
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 :)
25th Sep 2017, 12:48 PM
Daniele
Daniele - avatar
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
25th Sep 2017, 1:55 PM
Daniele
Daniele - avatar