Array initialization

I am trying to assign values ​​inside an array in a for loop condition:

#include <iostream>
using namespace std;
int* c;
int n;
int main()
{
    scanf("%d", &n);
    c = new int[n];
    for (int i = 0; i < n; c[i] = i++  )
    {
        printf("%d \n", c[i]);
    }
    return 0;
}

However, I do not get the desired output, for n = 5 0 1 2 3 4,. Instead, if I use the instruction c[i] = ++i, I get the output -842150451 1 2 3 4. Could you explain to me what we are doing so that my code behaves in the same way and how can I fix it?

+3
source share
5 answers

The value of an expression ++iis the value after it has ibeen incremented. Therefore, if it starts at 0, you assign the value 1 for the first time, and so on. You can see where the value was assigned, but asking why it got assigned there opens a can of worms.

i , i i++ ++i, undefined, " ". . . Undefined .

undefined , , - . -, 0 ( , , , , "" ), , , . 1 1 ..

, 5 c[5], , " " undefined , . , , , - .

, c[0] c[5], , i " " ". :

for (int i = 0; i < n; ++i) {
    c[i] = i;
    printf("%d \n", c[i];
}

- for, :

for (int i = 0; i < n; c[i] = i, ++i) {
}

, , , c[i] . , .

c[i] = i+1, ++i, ++i, c[i] = i, c[5] .

+8

, for , , :

-842150451 1 2 3 4

, c[0] , . , .

; for. :

for (int i = 0; i < n; ++i  )
{
    c[i] = i;
    printf("%d \n", c[i]);
}
+2

-, , " ". for (i < n ). , . , , , ?

-, c[i] = i++ c[i] = ++i ++. ++ - . , . . undefined. .

-, - for, , . , ? - .

+2

, c[i] = ++i undefined. undefined ++ (pre post) . , ++i -

c[1] = 1;
c[2] = 2;
...

, c[0] . ,

c[0] = 0;
c[1] = 1;

, .

c[i] = i;
i++;
+1

Your main problem is how the instructions in the for (;;) structure are broken and executed. The for (st1; st2; st3) structure is for identity:

st1;
while (st2) {
    <body>
    st3;
}

Therefore, your third statement c[i] = i++runs after the instruction printf, and you print uninitialized data.

The problem with pre-increment and post-increment hides this.

+1
source

Source: https://habr.com/ru/post/1795905/


All Articles