Could you help me understand this?(c++)

Mac Osxtopus

Ok, due to the board, i will not supply alligators to anything in this post, since it will not show anyways.

#include iostream

void cube(int *n, int num); /* the pointer, and num's 1st array element passed to this function*/

int i, nums[10]; /* i is for the numbers, *n is the pointer to num, which stores i that increases all the way to 10 */

for(i=0; i<10; i++) nums = i+1;//#'s 1-10
cout "Original Contents: ";
for(i=0; i<10; i++) cout nums ' ' ;//display
cout << '\n';

cube(nums, 10); // compute cubes

cout << "altered contents: ";
for(i=0; i<10; i++) cout nums ' ';/* display the cubed values of 1-10*/
return 0;

void cube(int *n, int num)
while(num) {
*n = *n * *n * *n;/* ??? I know this cubes....but where does the pointer point? it was never declared*/
num--;/* ??? what are these for? they just cancel out anyways*/


The pointer points to the first element in nums

num-- and n++ do not cancel out.
if it was *n++ then they would cancel out.
n++ moves the pointer to the next element of the array so that you are working with the next element next time throught the loop.
num-- decrements the value of num so that after changing the last element in the array num=0 which will exit the loop (and the function).



Unperson Spotter
Originally posted by Mac Osxtopus
Thank you, could you explain how it points though? :(
By the definition of evaluation of array names and argument passing by value, both inherited from C.

Suggested reading:
Brian W. Kernighan, Dennis Ritchie: The C Programming Language (Second Edition)

Bjarne Stroustrup: C++ Programming Language (Third Edition)