Solved

Confused about pointers

Posted on 2003-11-02
8
270 Views
Last Modified: 2010-04-15
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?
0
Comment
Question by:Tabris42
8 Comments
 
LVL 9

Assisted Solution

by:tinchos
tinchos earned 250 total points
ID: 9666065
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
 
LVL 5

Expert Comment

by:snehanshu
ID: 9666077
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
 
LVL 9

Expert Comment

by:tinchos
ID: 9666085
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
 
LVL 5

Expert Comment

by:snehanshu
ID: 9666095
OK, I misunderstood the question. Ignore my comment and go ahead with tinchos explanation.
...Snehanshu
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 5

Expert Comment

by:arjanh
ID: 9666132
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
 
LVL 5

Accepted Solution

by:
snehanshu earned 250 total points
ID: 9666213
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
 

Author Comment

by:Tabris42
ID: 9667533
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
 
LVL 9

Expert Comment

by:tinchos
ID: 9667687
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

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now