I am currently working on an exercise for my Programing Foundations I class.
This was the prompt:
Write a program that queries the user for the size and then declares an integer array of that size. Create a pointer to the first element of the array and then use the pointer to fill the array with random integer values in the range 3-17. Then print each element of the array with its address to the screen.
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
int size = 0;
cout << "How big do you want the array to be?: ";
cin >> size;
int array[size];
int* parray = &array[0];
cout << *parray << endl;
for(int i=0;i<size;i++)
{
cout << "Array[" << i << "] " << array[i] << endl;
}
/* use rand%17+3? */
return 0;
}
I just need emphasis on the pointer and how to use it. I've been looking at websites, but it's all theory based. I'd do better with an example. Any help would be much appreciated. Thanks.
If you need a pointer variable to point to the first thing in the array this is the line you are trying to do that with correct? int* parray = &array[0];
An array is just a pointer, a special kind of pointer, but a pointer nonethless therfore to create a pointer to the first element in the array simply type: int* parray = array
An array is just a pointer, a special kind of pointer, but a pointer nonethless therfore to create a pointer to the first element in the array simply type:
int* parray = array
can't you also use bracket notation on the parray just like you would on array(with the exception of the first one i.e.
parray == array[0]
parray[1] == array[1]
parray[2] == array[2]etc.
Yeah just tried out my own solution to your problem, and am getting random 18's and 19's as well. Tried using the more complex random number code from the forum linked by Danielsson but now it is only printing 3's
EDIT: You are probably making the same mistake I did look at this line in particular parray[i]=(rand()%17)+3;
It's a pretty easy fix once you realize what range of numbers you are actually assigning to the array.