Jared
Jared

Reputation: 33

C: Printing out the value and memory location of each element of an array using pointers?

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

Upvotes: 1

Views: 1696

Answers (1)

ikegami
ikegami

Reputation: 386621

  • 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);
    }
}

Upvotes: 3

Related Questions