C++/Qestion

Advertisement


Question
A_O_A
     
     
Q.1)    We use pointer subscript notation like

         char str[] = "Book";
         char *ptr;
         ptr = str;
         and we say that

         cout << ptr[1];
This will display only B. But why we use subscript notation with pointer variable and how this statement is valid.

Q.2)
     In pointer to pointer case, the first pointer cantain the address of the second pointer and the second pointer contain the address of the variable, which contain the desired value.
   
     But when we create an array and pointer like this we say that,

         int ary[] = {10,20,30,40};
         int *ptr;
         ptr = ary;
         cout << *ptr;

In this statement ptr = ary; ary is a pointer which contain the starting address of the first element. But when we derefrence the ptr pointer it gives the disired value. But in pointer to pointer we double derefrencing why?. We do single derefrencing with the pointer variable.
 
Regards
******************
Imran Ahmad Mughal
******************

Answer
Imran Ahmad Mughal, Thank you for your question.

1. The subscript notation in C++ is considered to be an abbreviation of pointer-based indexing:

char * ptr;
char arr[3];
// Same as cout << *(ptr + 2);
cout << ptr[2];
// Same as cout << *(arr + 2);
cout << arr[2];

2. Your example does not use double indexing or double indirection.

David Spector

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


David Spector

Expertise

Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.

Experience

I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Publications
Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

Education/Credentials
ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2016 About.com. All rights reserved.