Pages

Saturday, November 1, 2014

Pointers and Arrays

Pointers and arrays are intricately linked in the C language.

For Eg:

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

So, when we print

cout << nValue, the outupt is the address of  first element of nValue.
Therefore, we can say that nValue is a pointer that points to the first element of any array.

Thus, cout << nValue++ will be address of second element of nValue.

Also,

cout << *nValue will print the first element of nValue. This is called dereferencing pointers.e
and cout << *(nValue+1) will print the second element of nValue. Parentheses are used to ensure operator precedence is correct. Operator * has higher preference than +.


Also look at the following progam which uses the concept explained above.

#include <iostream>
using namespace std;

int main(){

const int nArraySize = 7;
char szName[nArraySize] = "Mollie";
int count=0;
for (char *pnPtr = szName; pnPtr < szName + nArraySize; pnPtr++)
{
   
    if(*pnPtr!=NULL){
  count++;   }
}

cout << szName << " has " << count << " alphabets" << endl;
}

No comments:

Post a Comment