dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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.cpp

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


//test2.cpp

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

 

 

 

 

 


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

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date