Interview Questions
Articles

If you can use pointers as array notation, explain similarity and differences between pointers and arrays?

Similarity between array and pointer:

Arrays are defined as const pointer. Array and pointer usage notation can be interchange.

Pointer can be used in array notation:

char* ptr=new char[3];
ptr[0]='a';
ptr[1]='b';

Array can be used in pointer notation:

char arr[]="abcde";
*(arr+4)='d';

 

Difference between array and pointer:

  1. Only for pointers, you need to explicitly allocate and deallocate memory, unless pointing to variable. This will be in heap unlike stack as in case for arrays.
  2. For pointer, memory to which it points can be resized using realloc. Array cannot be resized.
  3. You can take address of the pointer variable. Address of array will give you address for first element of that array. This is because array is just a name to a set of memory locations, whereas pointer is a variable.
  4. Sizeof pointer is always fixed. 8 byte for 64 bit machines and 4 bytes for 32 bit machine to store the start address( 64 bit or 32 bit ) of memory. Sizeof array is strlen of array + 1.