2

Look at this program. How does ptr get everything in array? I am a little confused.

  #include <stdio.h>
    int main()
    {
       int arr[] = {10, 20, 30, 40, 50, 60};
       int *ptr = arr;

       // sizof(int) * (number of element in arr[]) is printed
       printf("Size of arr[] %d\n", sizeof(arr));

       // sizeof a pointer is printed which is same for all type 
       // of pointers (char *, void *, etc)
       printf("Size of ptr %d", sizeof(ptr));
       return 0;

}
Sam Hosseini
  • 813
  • 2
  • 9
  • 17
CMan
  • 21
  • 2

5 Answers5

6

In this declaration

int *ptr = arr;

pointer ptr is initialized by the address of the first element of array arr.

An expression like this ptr[i] is considered by the compiler like *(ptr + i) where ptr + i results in a pointer that points to the i-th element of array arr

This has a consequence that instead of ptr[i] you can even write i[ptr] because in the both expressions there is used the same pointer arithmetic.

Try for example

std::cout << 6["Hello CMan"] << std::endl;

or

std::cout << &6["Hello CMan"] << std::endl;

So using pointer ptr that points to the first element of array arr and the so-called pointer arithmetic you can access any element of array arr.

The pointer does not accomodate the array. The pointer and the array occupy different memory regions. But the pointer stores the address of the first element of the array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

ptr will "refers" to first element of the array.

Every other element will be accessed by "adding" to base pointer address value, the size of the element multiplied by the index

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
0

The pointer is just a number representing the memory address of the start of the array. It does not contain any information about the array itself, so there is no limit on the size of the array it points to.

0

The type of ptr is int* and sizeof therefore returns the number of bytes used to store a pointer in memory. It does not return the size of the array.

Coert Metz
  • 894
  • 6
  • 21
0

You can find the answer for this question (and may be more than that) in these bellow link:

Are a, &a, *a, a[0], &a[0] and &a[0][0] identical pointers?

How to find the 'sizeof' (a pointer pointing to an array)?

Community
  • 1
  • 1
Van Tr
  • 5,889
  • 2
  • 20
  • 44