An in depth look at the difference between arrays and Pointers

  • 2020-04-01 21:24:56
  • OfStack

In C/C++, Pointers and arrays are used interchangeably in many places, which gives us the illusion that arrays and Pointers are completely equivalent. In fact, arrays and Pointers are quite different.
1. The difference in meaning between the two.
An array corresponds to an area of memory, and a pointer to an area of memory. Its address and capacity do not change over the lifetime, only the contents of the array can change; Unlike a pointer, the size of the memory area it points to can be changed at any time, and when the pointer points to a constant string, its contents cannot be modified, otherwise an error will be reported at run time.
Such as:
 
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
int main(void) 
{ 
  char*s1="123456789"; 
  char*s2="123456"; 
  strncpy(s1,s2,6); 
  printf("%s %sn",s1,s2); 
  return0; 
} 

No error is reported at compile time, but it is reported at run time because of an attempt to change the contents of s1. Since s1 and s2 refer to a constant string, the contents are unmodifiable and therefore will not pass at run time. And the following program can be run through:
 
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
int main(void) 
{ 
  char s1[10]="123456789"; 
   char s2[10]="123456"; 
   strncpy(s1,s2,6); 
   printf("%s %sn",s1,s2); 
   return0; 
} 

VC++ 6.0 can be compiled through the run, the reason is that the contents of the array can be modified, which fully reflects the difference between the pointer and the array, is not completely equivalent.
2. Calculate the difference of memory capacity.
The operator sizeof can be used to calculate the sizeof the array (bytes), while sizeof cannot be used to calculate the sizeof the memory referred to by the pointer. The result of sizeof(p) is always 4 or 2 (that is, the number of bytes occupied by the pointer variable in the memory unit, generally the pointer variable occupies 2 or 4 bytes of memory unit). When arguments are passed, the array is automatically degraded to a pointer of the same type.
Look at the following code and the results:
 
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
void function(int a[]) 
{ 
printf("%dn",sizeof(a)); 
} 
int main(void) 
{ 
int a[10]={1,2,3,4,5,6,7}; 
int*p=a; 
printf("%d %dn",sizeof(a),sizeof(p)); 
function(a); 
return0; 
} 

Related articles: