1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void printArray(int *num, int* size);
int main()
{
srand(time(NULL)); //seed
int size = 10; //array size
int numbers[size]; //array
for(int i = 0; i < size; i++) //get random numbers into array
{
numbers[i] = rand();
}
for(int i = 0; i < size; i++) //display array using pointer
{
cout << *(numbers + i) << endl;
}
cout << endl;
printArray(numbers, &size);
return 0;
}
/* I am horrible with the English language, and explaining things, but
* my best guess by "Pass the array size as a pointer to int" means that
* int size needs to be a int* size, and you pass the address as an argument
* into the second parameter field.
*
* Example:
* printarray(numers, &size);
* */
void printArray(int *num, int* size)
{
/* If my guess is right, that means you also need to modify this a bit */
int *ptr = num;
cout << "ptr: " << endl;
/* Since size is a pointer, you have to deference it with the dereference
* operator *. You deference it because you want the value of the size
* instead of the memory address */
for(int i = 0; i < *size; i++)
{
cout << *(ptr + i) << endl;
}
}
|
I don't quite understand them |
A pointer can be used to point to a memory address.
We can also reassign the memory address they are pointing to.
For example, right now p (which is a pointer) is pointing to
the memory address that contains a value of 20.
If we wanted print it, we could do
|
std::cout << p << std::endl;
|
but that would print out a memory address. Instead, we have to dereference it
using the dereference operator *
|
std::cout << *p << std::endl; // prints a value now instead of an address
|
The thing with pointers, as mentioned, as that we can repoint them to another
address (as long as its the same type). So we can say that p points to the
address of the value 10 now.
and when we print this (assuming we print it by dereferencing it as well),
we will get the value of 10.