1

I have generated a random array inside the main function, How can I properly print it out using a separate function and inside the function print out the value and memory location of each element of that array using pointers. Here is my code so far:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void printArray(int *pointertoArray, int *Size);

int main (void)
{
 srand(time(NULL));
 int array[10];
 int *pointer = NULL;
 for(int i = 0; i < size; i++)
 {
     array[i] = rand();
     *pointer = array[i];
     printArray(*pointer,size);
 }
}
void printArray(int *pointerToArray, int *size)
{
    int i = 0;
    do
    {
        printf("\nValue %d = %p ",i,*pointerToArray);
        i++;
    }
    while(i < size);
}

Here is what I am trying to achieve:

    value 1 = 0x7fff0815c0e0
    .....
    value 10 = 0x7fff0815c0ec
0

1 Answer 1

3
  • int *size should be int size. You don't pass a pointer, and you don't need a pointer.
  • Actually, size_t size would be more appropriate.
  • The call to printArray should be located after the loop. You only want to print the array once.
  • printArray(*pointer, size); should be printArray(array, size);.
  • pointerToArray should be named array or pointerToInts.
  • The value of the element is pointerToArray[i], not i.
  • The address of the element is pointerToArray+i, not *pointerToArray.
  • The loop in printArray should be top-tested. (No reason for it to be bottom tested, so play it safe.)
  • main is declared to return an int, but doesn't.

We get,

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void printArray(int *array, size_t size);

int main() {
   srand(time(NULL));
   int array[10];
   for (int i = 0; i < size; ++i) {
      array[i] = rand() % 1000;
   }

   printArray(array, sizeof(array)/sizeof(array[0]));
   return 0;
}

void printArray(int *array, size_t size) {
   for (int i = 0; i < size; ++i) {
      printf("Value @ %p = %d\n", array+i, array[i]);
   }
}

Alternative:

void printArray(int *pointerToInt, size_t size) {
    for (; size--; ++pointerToInt) {
       printf("Value @ %p = %d\n", pointerToInt, *pointerToInt);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.