The Difference Between Pointers and Arrays

Some programmers believe that int a[] and int * a are equivalent.Also some C++ books to say that pointers and arrays are almost same. This belief usually leads to hard to find bugs in the program. Suppose we have a function:

 void f(int *p);

We can call it either passing a variable of type int * or int[]. For example:

 	int * p;	int a[10];	...	//initialize a and p here..	...	...	//we can call f by either passing p or a	f(a);	f(p);

The code generated by the compiler when accessing the pointers and array variables is different. When we say int * p, there exists a physical memory that points to an integer. But when we say int a[], there is no such location, and it is the compiler that generates the proper addresses wherever it is referenced.

Suppose you have a declared an array in a source file and want to use the array from another source file. The common practice is to declare the array as extern in the file where it is being used. The following program will crash:

 //test1.cppextern int a[5] = {1,2,3,4,5};...//test2.cppextern int * a;main(){   a[0] = 10;}

It crashes because in test2.cpp, the extern declaration is not consistent with that of in test1.cpp. The correct extern declaration in test2.cpp should be as below:

 extern int a[];

Most compilers won

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: