1

This is a sample code from tutorialspoint site. I do not understand why there is this assignment under the first comment in the code. Why we assign whole array to the pointer and not just an address. Should it be ptr = &var?

#include <stdio.h>

const int MAX = 3;

int main () {

   int  var[] = {10, 100, 200};
   int  i, *ptr;

   /* let us have array address in pointer */
   ptr = var;
    
   for ( i = 0; i < MAX; i++) {

      printf("Address of var[%d] = %x\n", i, ptr );
      printf("Value of var[%d] = %d\n", i, *ptr );

      /* move to the next location */
      ptr++;
   }
    
   return 0;
}
wallshock
  • 101
  • 6
  • *"Should it be ptr = &var?"* - No, that's a type error. See duplicate for explanation. – klutt Apr 26 '22 at 12:58
  • Also check out https://stackoverflow.com/questions/46505581/assigning-pointers-to-variables-vs-assigning-pointers-to-arrays-in-c – hyde Apr 26 '22 at 12:58
  • 3
    The name of an array is actually the address of first element of that array. Either you should do `ptr = var;` or `ptr = &var[0];`, both are valid. – Avinash Apr 26 '22 at 12:59

0 Answers0