2016-10-13 4 views
-1

Ich habe dieses Stück C-CodeFalscher Wert von printf gedruckt wird

#include <stdio.h> 

int main(){ 
     int i , j , m , A[5]={0,1,15,25,20}; 
     i = ++A[1]; 
     printf("%d:\n",i); 

     j = A[1]++; 
     printf("%d:\n",j); 

     m = A[i++]; 
     printf("%d:\n",m); 

     printf("%d %d %d",i,j,m); 
     return 0; 
} 

und es ist Ausgang

2: 
2: 
15: 
3 2 15 

soll nicht der printf Druck ist der Wert als 2, 2, 15, aber warum ist es Drucken 3, 2, 15

PS: Ich habe diesen Code wirklich nicht missbraucht, jemand anderes tat (mein Professor vielleicht) und ich lerne gerade C.

+0

Nicht von '++' missbrauchen. Vielleicht Klammern (um die Lesbarkeit zu erhöhen), also '(A [1]) ++' anstelle von 'A [1] ++'. Initialisiere jede Variable. Kompilieren Sie alle Warnungen und Debug-Informationen (z. B. 'gcc -Wall -g 'bei Verwendung von [GCC] (http://gcc.gnu.org/) ...). Lesen Sie http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html –

Antwort

0

Mal sehen, was wir hier bekommen ..

int i, j, m, A [5] = {0,1,15,25,20};

i = ++A[1]; // takes the value of A[1], increment it by 1 and assign it to i. now i = 2, A[1] = 2 
    printf("%d:\n",i); 
    j = A[1]++; // takes the value of A[1](which is 2), assign it to j and increment the value of A[1] by 1. now j = 2, A[1] = 3 
    printf("%d:\n",j); 

    //remember the value of i? its 2 
    m = A[i++]; // takes the value of A[2](which is 15), assign it to m and increment the value of i by 1. now m = 15, i = 3 
    printf("%d:\n",m); 

    printf("%d %d %d",i,j,m); // Hola! we solve the mystery of bermuda triangle :) 
    return 0; 
1

Die Linie

m = A[i++]; 

inkrementiert die Variable i in-place, nachdem es den cooresponding Wert aus dem Array A. erhält

+1

Ich bin und Idiot, Danke. –

1

i als Teil der unter Anweisung inkrementiert

 m = A[i++]; 
0

m = A [i ++];

dieser Code zuweisen A [2], die 15 auf die Variable m ist, und dann +1 auf den aktuellen Wert von i zu werden 3.