Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Apr 23, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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

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:

extern int a[5] = {1,2,3,4,5};


extern int * a;

   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
Rajesh Chathapuram
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date