devxlogo

The Difference Between Pointers and Arrays

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);

size=3>
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);

size=3>
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;}

size=3>
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[];

size=3>
Most compilers won

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist