Question:
c++ Array of 50, but filling only the first 10 using pointers?
daisy i
2014-02-24 23:39:22 UTC
I want to create an array of 50 elements and only fill the FIRST 10 with random numbers using the random number generator, which will result in the rest of the 40 elements to be zero.
I can't seem to get it right.
Here is my main:
int main()
{
int Array[50],
*p1;
return 0;
}

function prototype:
void fillArray ( int Array[], int *p )
{
srand( time(0) );
for (int i = 0; i < 10; i++) // less than 10 because only 10 filled???
{
for ( int j = 0; j < i; j++) //within previous loop
{
p[i] = rand() % 11;
p++; // moving to next location, not sure if this is right.
}
}
}
I have a hard time with pointers because I just learned them. It displays random numbers in all 50 elements. I know I'm doing something wrong with the pointers. Any help is appreciated, thank you!
Three answers:
cja
2014-02-26 09:27:30 UTC
You can, and should, initialize Array to all zeros on declaration. You don't show a call to fillArray, so I'm not sure what you have in mind with the argument int *p. You probably don't need it. The function fillArray needs to be given a pointer to an array, and a size. You can use an int* in fillArray to access the elements of the array. You dereference the pointer to store at a location, e.g. *p = value; You increment the pointer to reference the next location in the array: p++, or ++p, or p = p + 1, or p += 1. You can combine the store and advance operations in one statement. First dereferencing to store, then incrementing: *p++ = value.



Also, you should only seed the random number generator once per program execution, so move the srand call to the beginning of main.



Here's an example of what your program should look like:



#include

#include

#include



using namespace std;



void fillArray(int *, size_t);



const size_t aSize = 50;

const size_t N = 10;



int main(int argc, char *argv[]) {

    int Array[aSize] = { 0 };



    srand(time(0));

    fillArray(Array, N);

   

    for (size_t i = 0; i < N; i++) {

        cout << Array[i] << " ";

    }

    cout << endl;

    return 0;

}



void fillArray (int *a, size_t n) { {

    int *p = a;

   

    for (size_t i = 0; i < n; i++)

        *p++ = rand() % (n + 1);

    }

}



#if 0



Sample output:



5 7 5 10 1 10 9 6 8 1



#endif
Bacalao
2014-02-25 01:27:39 UTC
There is always something in memory, so when you declare 50 integer variables they're filled with garbage. Try initializing the entire array to 0 using a for loop and then assign a random value to the first ten. You should notice the rest of the array being 0.
Vlar
2014-02-25 06:44:08 UTC
Your assumption about "p++" moving the pointer to the next array element is correct. :) although in your program you probably don't need to use it as you are using p[i] to access each element.



Your 2nd for loop is redundant.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...