Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Saturday, 15 August 2015

In the last post we discussed the concept of Dynamic memory and new, delete operators. today we'll discuss some other C++ concepts.

 Including User Defined Header Files:

Uptil now we have only seen examples where we use C++ standard library header files. these are included according to the following mechanism.
when including our own header files C++ the following mechanism is used:

an example is given below:

Namespaces:

A C++ program has identifiers in different scopes, Sometimes these scopes overlap which can lead to problems;
         So to counter this we have  Namespaces, which define scope
        Place identifiers and variables within namespace
        Access with namespace_name::member
        Unnamed namespaces are global
          Need no qualification
        Namespaces can be nested
          using statement
        using namespace namespace_name;
        Members of that namespace can be used without preceding namespace_name::
          Can also be used with individual member
        Examples
          using namespace std
          Discouraged by some programmers, because includes entire contents of std
          using namespace std::cout
          Can write cout instead of std::cout
Consider the following examples:
Example 1:
#include <iostream>
using namespace std;
 namespace first
 {
int x = 5;
 int y = 10;
 }
 namespace second
{
 double x = 3.1416;
 double y = 2.7183;
 }
int main ()
 {
using first::x;
 using second::y;
cout << x << endl;
 cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
 return 0;
 }



Properties of Namespaces:

We can have more than one namespace of the same name. This gives the advantage of defining the same namespace in more than one file (although they can be created in the same file as well). The “anonymous” namespace you have created will only be accessible within the file you created it in.

Typedef:

typedef is a Keyword which:
–Makes synonyms (aliases) for previously defined data types
•Does not create new type, only an alias
–Creates shorter type names
Example:
typedef int* intPtr;
–Defines new type name intPtr as synonym for type int*
intPtr myintPtr;
int * myintPtr;          //Both are same

Bitwise Operators:

Data is  represented internally as sequences of bits
        Each bit can be 0 or 1
        8 bits form a byte
          char is one byte
          Other data types larger (int, long, etc.)
        Low-level software requires bit and byte manipulation
          Operating systems, networking
          So for bit and byte manipulation we have "Bit operators", these contain:
        & (bitwise AND)
          1 if both bits 1, 0 otherwise
        | (bitwise inclusive OR)
          1 if either bit 1, 0 otherwise
        ^ (bitwise exclusive OR)
          1 if exactly one bit is 1, 0 otherwise
          Alternatively: 1 if the bits are different
        ~ (bitwise one's complement)
          Flips 0 bits to 1, and vice versa
        << (left shift)
          Moves all bits left by specified amount
          Fills from right with 0
          int x = 16;
          x = x << 2;
        >> (right shift with sign extension)
          Moves bits right by specified amount
          Fill from left can vary





Some Other C++ Concepts

Wednesday, 12 August 2015

As you may remember from your lesson on arrays, we initially declared the size of the array in our code. However, what if, at run time, the user only wanted to enter five elements in the ten element array we declared? That would be a waste of space. Conversely, if our array is smaller than what the user wants, that would pose another problem. To overcome this, we use the concept of dynamic memory, where the array size is entered by the user during the running of the application.

Dynamic Memory

          Until now, we have only had as much memory as we have requested in declarations of variables, arrays etc
          The size of all of them was fixed BEFORE the execution of the program.
          What if we need a variable amount of memory
          That can only be determined DURING the program execution (runtime).
          For example, in case that we need user input to determine the necessary amount of space?

The answer is dynamic memory
We can accomplish this using the operators new and delete

Operators "new" and "new[]"

          new: to request dynamic memory
          new is followed by a data type
          and optionally the number of elements required within brackets [].
          Returns a pointer to the beginning of the new block of assigned memory.
                pointer = new type // to assign memory to contain one single element of type
               or
               pointer = new type [elements]  // to assign a block (an array) of elements of type.

int * b;
b = new int[5];
          The operating system will assign space for 5 elements of type int
          And will return a pointer to its beginning
          That has been assigned to b.
          Therefore, now, b points to a valid block of memory with space for 5 int elements. 


Why use pointers as arrays?

•the size of an array must be a constant value
•Which limits its size to what we decide at the moment of designing the program before its execution
•Whereas the dynamic memory allocation allows assigning memory during the execution of the program
•using any variable, constant or combination of both

Dynamic Memory Implementation


•The dynamic memory is generally managed by the operating system
•Shared between several applications
•So there is a possibility that the memory exhausts.
•If so, the operating system cannot assign the memory that we request with the operator new
•A null pointer will be returned.
•For that reason it is recommended to always check to see if the returned pointer is null after a call to new

int * b;
   b = new int [5];
   if (b == NULL) {
       // error assigning memory. Take
     //measures.
   }; 

Operators "delete"

          Once the dynamic memory is no longer needed it should be freed
          So that it becomes available for future requests of dynamic memory.
          The operator delete exists for this purpose
                delete pointer;
                or
               delete [] pointer;

          The first expression should be used to delete memory allocated for a single element
          The second one for memory allocated for multiple elements (arrays).
          In most compilers both operators are equivalent

"new" and "delete"

Take a look at an example code to see the implementation of the operators:





Dynamic Memory and "new" and "delete" Operators

Monday, 10 August 2015

Last time we wrapped up the topic of Pointers and Strings , today we will have a look at <cctype> which is a very important and useful library in C++.

Character Handling Library or <cctype> is a library in C++
–        It has functions to perform tests and manipulations on characters
–       You pass character as argument
•          Character represented by an int
–        char does not allow negative values
•          Characters often manipulated as ints
•          EOF usually has value -1
•   In the upcoming example you will witness the usage of:
–        isalpha( int c )
•          (All character functions take int argument)
•          Returns true if c is a letter (A-Z, a-z)
•          Returns false otherwise
–        isdigit
•          Returns true if digit (0-9)
–        isalnum
•          Returns true if letter or digit (A-Z, a-z, 0-9)
–        isxdigit
•          Returns true if hexadecimal digit (A-F, a-f, 0-9)
  



Some other functions of the character handling Library are:
        islower

          Returns true if lowercase letter (a-z)
        isupper
          Returns true if uppercase letter (A-Z)
        tolower
          If passed uppercase letter, returns lowercase letter
        A to a
          Otherwise, returns original argument
        toupper
          As above, but turns lowercase letter to uppercase
        a to A
        isspace
          Returns true if space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v'
        iscntrl
          Returns true if control character, such as tabs, form feed, alert ('\a'), backspace('\b'), carriage return, newline
        ispunct
          Returns true if printing character other than space, digit, or letter
          $ # ( ) [ ] { } ; : %, etc.
        isprint
          Returns true if character can be displayed (including space)
        isgraph
          Returns true if character can be displayed, not including space

 Some of these are better explained through there usage in the following example:




Character Handling Library

Thursday, 6 August 2015

Continuing with the previous post, today we will further study pointers and strings.

Pointer Expressions and Pointer Arithmetic:

Pointer arithmetic is of the following types:

–Increment/decrement pointer  (++ or --)
–Add/subtract an integer to/from a pointer( + or += , - or -=)
–Pointers may be subtracted from each other
but remember that pointer arithmetic is meaningless unless performed on pointer to array
consider an example where there is a 5 element int array on a machine using 4 byte integer space.
vPtr points to first element v[ 0 ], which is at location 3000
Vptr = v or vptr = &v[0]
vPtr += 2; sets vPtr to 3008

vPtr points to v[ 2 ]
 when subtracting pointers (must both point to the same array, if not then LOGIC ERROR)
–Returns number of elements between two addresses
  vPtr2 = &v[ 2 ];
vPtr = &v[ 0 ];
vPtr2 -
vPtr = 2
As far as pointer assignment is concerned:
–Pointer can be assigned to another pointer if both are of same type
–If not of the same type, cast operator must be used
–Exception: Void Pointer: pointer to void (type void *)

Void Pointer: Pointer to void (type void *):

int nValue = 5;
void *pVoid = &nValue;    //no need for casting
// can not dereference pVoid because it is a void pointer
int *pInt = static_cast<int*>(pVoid); // cast from void* to int*

cout << *pInt << endl; // can dereference pInt

Void Pointer:

the code given below shows an example of void pointers:

void f (void *,void*,int);
main()
{
int x=9,y=5;
char r='w',t='z';
                f(&r,&t,sizeof(r));
f(&x,&y,sizeof(x));
                cout<<x<<endl;
cout<<r<<endl;
}
void f(void* x, void* y, int sizeofptr)
{
int *nptr1, *nptr2;
char *nptr3, *nptr4;
if (sizeofptr == sizeof(int))
{ nptr1=(int* )x;
nptr2=(int* )y;
*nptr1=*nptr1**nptr2;}
else
{nptr3=(char* )x;
nptr4=(char* )y;
*nptr3=toupper(*nptr3);}
}

Relationship between Arrays and Pointers:

Arrays and pointers are closely related:
        Array name is like a constant pointer
        Pointers can do array subscripting operations:
                                    int b[5];
                                    int *bptr;
You can point ‘bptr’ to array ‘b’ using either;
                                    bptr = b;    //remember name of array is constant pointer to address of the first                                                           location of array  
                        Or
                                    bptr = &b[0];
Array elements can easily be accessed with pointers
        Element b[ n ] can be accessed by  *( bPtr + n )
          Called pointer/offset notation
          ‘n’ is the offset
          DO NOT forget the brackets, since * bPtr + n  will simply add n to *bPtr
        Accessing array addresses with pointers:
          &b[ 3 ] same as bPtr + 3
        Array name can be treated as pointer;
          b[ 3 ] same as *( b + 3 )
          This is possible since name of the array is a pointer itself.
        Pointers can be subscripted (pointer/subscript notation)
          bPtr[ 3 ] same as b[ 3 ]





Array of Pointers:

An array can contain pointers
–This is commonly used to store array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds",
                
 "Clubs", "Spades" };
–Each element of suit points to char * (a string)
–Array does not store strings, only pointers to strings

suit array has fixed size, but strings can be of any size

Pointer & Strings: Part Three

Sunday, 2 August 2015

Previously we completed the concept of Arrays (parts one, two  three and four), today we will discuss the basics of Pointers.

Pointer Variable Declarations and Initialization

•      Pointer variables:
     Contain memory addresses as values
     Normally, variable contains specific value (direct reference)
     Pointers contain address of variable that has specific value (indirect reference)
      Indirection
     Referencing value through pointer
      Pointer declarations
     * indicates variable is pointer
int *myPtr;
     declares pointer to int, pointer of type int *
     Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
      Can declare pointers to any data type
      Pointer initialization
     Initialized to 0, NULL, or address
        0 or NULL points to nothing, and is called ‘Null Pointer’

Pointer Operators:

& (address operator)
–Returns memory address of its operand
–Example
  int y = 5;
int *yPtr;
yPtr = &y;    // yPtr gets address of y

yPtr “points to” y
* (indirection/dereferencing operator)
*yPtr returns y (because yPtr points to y).
*yptr = 9;      // assigns 9 to y
     cout<<*yptr
     cin>>*yptr;
*  and & are inverses of each other

Calling Functions by Reference

          3 ways to pass arguments to function
        Pass-by-value
        Pass-by-reference with reference arguments
        Pass-by-reference with pointer arguments
          Pass-by-reference with pointer arguments
        Use pointers and indirection/dereferencing operator
        Pass address of argument using & operator
        * operator used as alias/nickname for variable inside of function






Pointer & Strings

 
Codexify © 2015 - Designed by Templateism.com