hjalpmig
hjalpmig

Reputation: 702

creating/printing array using pointers in C

So for some Uni work I need to create an array using a function (my first time with C functions and pointers) but store the array as a pointer because i dont think C can use arrays in functions? And then also use another function to print out each element in the array. The code i use in main is:

    int* x = get_lotto_draw();
    print_array(x);

And then my functions are:

int* get_lotto_draw() //Returns an array of six random lottery numbers 1-49
{
     int min = 1;
     int max = 49;
     int counter = 0;

     srand(time(NULL));
     int r = rand()%(max-min)+min;

     int *arrayPointer = malloc(6 * sizeof(int));

     for(counter = 0; counter <= 5; counter++)
     {
                 arrayPointer[counter] = r;
     }  

     return arrayPointer;
}



void print_array(int * array) //Print out the content of an array
{
     int i = 0;
     int printerArray[6] = {0, 0, 0, 0, 0, 0};

     for(i = 0; i <= 5; i++)
     {
           printerArray[i] = array[i];
     }

     printf("array = %d", array);
     printf("printerArray = %d", printerArray);

     for(i = 0; i <= 5; i++)
     {
           printf("Array element %d : %d\n", i, printerArray[i]);
     }
}

But im doing something wrong, and either the array isnt getting created correctly, or the print isnt working correctly. Thanks for your time.

Upvotes: 2

Views: 186

Answers (2)

mah
mah

Reputation: 39807

What you want is:

void print_array(int * array) //Print out the content of an array
{
     int i = 0;

     for(i = 0; i <= 5; i++)
     {
           printf("Array element %d : %d\n", i, array[i]);
     }
}

Upvotes: 1

Dabo
Dabo

Reputation: 2373

Following two lines could provoke undefined behavior

 printf("array = %d", array);
 printf("printerArray = %d", printerArray);

you can't use %d here, as array and printerArray decays to pointers in this context and in order to print pointer you should use %p and cast your arrays to void * (thanks to @user3447428 for his comment about cast )

Upvotes: 1

Related Questions