Advertisement
Guest User

Untitled

a guest
Jun 15th, 2013
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main() {
  4.     int arr[3][4];
  5.    
  6.     //  having the { on the same line as for example "for" and "if" is a more generally accepted style.
  7.     for (int i = 0; i < 3; i++) { // it's nicer to have a space after the "for", and also "if" et cetera, because it's more readable.
  8.         for (int j = 0; j < 4; j++) {
  9.             arr[i][j] = i * j;
  10.         }
  11.     }
  12.  
  13.    
  14.     // I made the code look a bit weird below to make it easier to comment.
  15.    
  16.     for (
  17.  
  18.         int (*p)[4] = arr;  // creates a pointer to "arr". This is basically p[0]... (I guess p[0][4] is a better explanation.)
  19.         p != arr + 3;       // checks if the current index of the array "p" is less than 3 - so it doesn't go out of bounds
  20.         ++p                 // increment the pointer by one so that it goes one up. Before you call ++p, it is at p[0], but when you call ++p - it will become p[1]. It increments the index of the array.
  21.  
  22.         ) {
  23.  
  24.         for (
  25.  
  26.             int *q = *p;    // pointer to array that the current index of p is at. so if p is at arr[1], then q becomes arr[1][0].
  27.             q != *p + 4;    // checks if the current index of the array "q" is less than 4 - so it doesn't go out of bounds
  28.             ++q             // increment the pointer by one so that it goes one up. Before you call ++q, it is at q[?][0], but when you call ++q - it will become p[?][1]. The ? is basically any index that p is. an "i" if you will.
  29.  
  30.             ) {
  31.  
  32.             std::cout << *q << ", ";    // prints out the value of the current index of q. q got first assigned to as the index of p, but remember we incremented the q pointer? This is arr[p][q] - so it's the element.
  33.                                         // the * before q deferences the pointer and you get the value that the pointer points to.
  34.         }
  35.     }
  36.    
  37.     std::cin.get(); // system("pause") is not recommended
  38.    
  39.     return (0); // it's nicer to have pharanteses around the return value.
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement