Output is 21212 but how? And what does m++ here means and even after declaring i as int 2 times why it's not showing any error? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 6

Output is 21212 but how? And what does m++ here means and even after declaring i as int 2 times why it's not showing any error?

#include <iostream> using namespace std; void f(int m[5]) { for(int i=0;i<3;i++){ m[i]*=2; m++;} } int main() { int a[5]={1,1,1,1,1}; f(a); for(int i=0;i<5;i++) cout<<a[i]; return 0; }

1st May 2017, 3:44 PM
Vineet Mishra
Vineet Mishra - avatar
3 Antworten
+ 15
as m is a pointer to an array when you increase the value of m the effect is like you shift the 0 index by one, in this case: m : 1 1 1 1 1 // entry point ^ // pointer is here m : 2 1 1 1 1 // m[0] = 2 ^ m : 2 1 1 1 1 ^ // m++ m : 2 1 2 1 1 // m[1] = 2 ^ m : 2 1 2 1 1 ^ // m++ m : 2 1 2 1 2 // m[2] = 2 not sure if that is clear enough, but that's the best I can do in text 😃
1st May 2017, 3:54 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 5
m++ acts as an address skipping element here. If you have been noticing, f function's for loop sets to be repeated for 3 times and inside the for loop you see that after each multiplication, m shifts the address of the last indexed cell, 4 bytes further ( since it's an int type) and as a result, the multiplication has an alternate pattern.
1st May 2017, 4:19 PM
Babak
Babak - avatar
+ 4
Thank you Nikolay Nachev but why it's not showing any error even after declaring i as int 2 times?
1st May 2017, 4:00 PM
Vineet Mishra
Vineet Mishra - avatar