• C

Confused about pointers

I'm a little unfamiliar with pointers, and badly need some help with them. I have a function here, that creates 300 random 4 digit numbers. I am required to print this array out in another function. (Or in main, it doesn't really matter, but preferrably from another function). Here is the function:

int randomgenerator()
{
     int limit = 1000; int max= 9999; int i; int randentry;
     int randomnumbers[300];
     printf("Enter a seed for random generation: ");
     scanf("%d", &randentry);
     if (randentry == 0){
        randentry == time(0);
     }
     printf("\n");
     srand(randentry);
     for(i = 0;i < 300; i++){
          randomnumbers[i] = (rand() % (max - limit)) + limit;
     }
     for(i = 0;i < 300; i++){
          printf("%d", randomnumbers[i]);
          if (i%14){
              printf(" ");
          }else{
              printf("\n");
          }
     }
      printf("\n");
      system("PAUSE");
      return 0;
}

Obviously the return statement is wrong, but how would I be able to take the array from this function so I can print it, or use it in other functions?
Tabris42Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tinchosCommented:
I believe that if you need to return an array, then you should return an integer pointer so that all the elements can be accessed.

But in order to do this, then the function must store the array in the heap, as when you store an array as you did, it is stored in the stack and that memory is released after the execution exits the function.


int *randomgenerator( int cantElements )
{
    int limit = 1000; int max= 9999; int i; int randentry;
    int *randomnumbers = (int *)malloc( cantElements * sizeof( int ) );
    printf("Enter a seed for random generation: ");
    scanf("%d", &randentry);
    if (randentry == 0){
       randentry == time(0);
    }
    printf("\n");
    srand(randentry);
    for(i = 0;i < cantElements; randomnumbers++, i++){
         *randomnumbers = (rand() % (max - limit)) + limit;
    }
    for(i = 0;i < cantElements; randomnumbers++, i++){
         printf("%d", *randomnumbers );
         if (i%14){
             printf(" ");
         }else{
             printf("\n");
         }
    }
     printf("\n");
     system("PAUSE");
     return randomnumbers;
}

and then you'll use it like this

// Code

int * vector = randomgenerator( 300 );

for( int i = 0; i < 300; i++ )¨
     printf( "%d ", *vector );

and you don't have to forget to free the memory of the array

free( vector );

Hope this helps

Tincho
0
snehanshuCommented:
Tabris42,
  You have done all the hard work, and now need help with the easy part!
:-)
  Recently, I've posted this explanation in many questions and here it is again:
Well, in C, an array is infact a pointer.
  When you declare
int randomnumbers[300];
  What you are saying is that there is a pointer randomnumbers which is assigned 300 continuous memory locations of type integer.
  A pointer contains address of a memory location.
  When you access randomnumbers as randomnumbers[n], you are effectively asking the compiler to deal with the value contained at the address contained in randomnumbers + 0.
  So, that's abput pointers in brief.
  Now, to pass an array to a function, you can simple pass the address of the array's starting location.
  That means, your function should accept a pointer as follows:
  int mydisplay( int *myarray)
  {
    //use myarray[0] to myarray[299] for displaying
  }
  Now, when you call mydisplay from main like
mydisplay(randomnumbers);

Hope that explained something.
...Snehanshu
0
tinchosCommented:
However, I would rather have the array created and released in the same function, so I would do like.......

void randomgenerator( int * randomnumbers, int cantElements )
{
   int limit = 1000; int max= 9999; int i; int randentry;
   printf("Enter a seed for random generation: ");
   scanf("%d", &randentry);
   if (randentry == 0){
      randentry == time(0);
   }
   printf("\n");
   srand(randentry);
   for(i = 0;i < cantElements; randomnumbers++, i++){
        *randomnumbers = (rand() % (max - limit)) + limit;
   }
   for(i = 0;i < cantElements; randomnumbers++, i++){
        printf("%d", *randomnumbers );
        if (i%14){
            printf(" ");
        }else{
            printf("\n");
        }
   }
    printf("\n");
    system("PAUSE");
}

and then you'll use it like this

// Code

int vector[300];

randomgenerator( vector, 300 );

for( int i = 0; i < 300; i++ )¨
    printf( "%d ", *vector );


// Or

int *vector = (int *)malloc( 300 * sizeof( int ) );

randomgenerator( vector, 300 );

for( int i = 0; i < 300; i++ )¨
    printf( "%d ", *vector );

free( vector );
0
Challenges in Government Cyber Security

Has cyber security been a challenge in your government organization? Are you looking to improve your government's network security? Learn more about how to improve your government organization's security by viewing our on-demand webinar!

snehanshuCommented:
OK, I misunderstood the question. Ignore my comment and go ahead with tinchos explanation.
...Snehanshu
0
arjanhCommented:
Hi Tabris,

An array is just a pointer to the first item in the array. So if you return randomnumbers (or randomnumbers[0] which is the same), you can then use it later on. I would do something like this:

void randomgenerator( int* randomnumbers ) {
    ...your code...
     for(i = 0;i < 300; i++){
          randomnumbers[i] = (rand() % (max - limit)) + limit;
     }
    ...more code...
}

int main() {
    int randomnumbers[300];
    int i;

    randomgenerator( randomnumbers );
    for(i = 0;i < 300; i++){
          printf("%d", randomnumbers[i]);
          if (i%14){
              printf(" ");
          }else{
              printf("\n");
          }
    }
}

Cheers,
Arjan
0
snehanshuCommented:
Now that i've understood your question, here's another alternate for you.
You can declare the array inside your randomgenerator function to be static: that way, it will remain in the memory until your program stops.
Then, you could change the function type to int * and return the address of your array from your function by changing the return statement to
return randomnumbers;
Note that in this case, you would always have a SINGLE set of 300 random numbers: everytime you call randomgenerator, the values will be changed.

So, your function becomes

int * randomgenerator()
{
     int limit = 1000; int max= 9999; int i; int randentry;
     static int randomnumbers[300];
     printf("Enter a seed for random generation: ");
     scanf("%d", &randentry);
     if (randentry == 0){
        randentry == time(0);
     }
     printf("\n");
     srand(randentry);
     for(i = 0;i < 300; i++){
          randomnumbers[i] = (rand() % (max - limit)) + limit;
     }

      return randomnumbers;
}

Then you can call randomgenerator from main like

int main ()
{
  int * myarray;
  int i;
  myarray = randomgenerator;
     for(i = 0;i < 300; i++){
          printf("%d", myarray[i]);
          if (i%14){
              printf(" ");
          }else{
              printf("\n");
          }
     }
      printf("\n");
      system("PAUSE");
      return 0;

}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Tabris42Author Commented:
Guys, your answers are very helpful, but the code you're giving me totally screws up the numbers I'm supposed to be getting.
0
tinchosCommented:
The problem is the following

When you assign the values to the vector, then, you continue printing the pointer from the end of the vector, so you're printing places where the data has not been assigned..........


    for(i = 0;i < cantElements; randomnumbers++, i++){
         *randomnumbers = (rand() % (max - limit)) + limit;
    }
////////////////////////////////////////////////////////////////////////////////////
Here, as you don't reassign randomnumbers, you will print all the values stored after the end of the data stored
////////////////////////////////////////////////////////////////////////////////////

    for(i = 0;i < cantElements; randomnumbers++, i++){
         printf("%d", *randomnumbers );
         if (i%14){
             printf(" ");
         }else{
             printf("\n");
         }
    }

Do as the following

void randomgenerator( int * randomnumbers, int cantElements )
{
   int limit = 1000; int max= 9999; int i; int randentry;
   int * tempPointer;

   printf("Enter a seed for random generation: ");
   scanf("%d", &randentry);

   if (randentry == 0){
      randentry = time(0);
   }
   printf("\n");
   srand(randentry);

   // Assign the pointer to use with the original origin of the vector
   tempPointer = randomnumbers;
   for(i = 0;i < cantElements; tempPointer++, i++){
        *tempPointer = (rand() % (max - limit)) + limit;
   }

   // Reassign the pointer to use with the original origin of the vector
   tempPointer = randomnumbers;
   for(i = 0;i < cantElements; tempPointer++, i++){
        printf("%d", *tempPointer );
        if (i%14){
            printf(" ");
        }else{
            printf("\n");
        }
   }
    printf("\n");
    system("PAUSE");
}

I tested this and works just fine

Cheers

Tincho
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.