Lecture2.2 Basicsofc++programming
Lecture2.2 Basicsofc++programming
You can do a lot of programming in C++ without using pointers, you will find them essential to obtaining the most
from the language.
Now,
Let‘s create a pointer that stores this address. SAME OR DIFFERENT ??
Int *ptr=&x;
cout<<ptr; o/p:0x….
Q:Why would I use a pointer just to assign the value to the variable??
A:The above example was just an example to demonstrate on pointers.
This is not the type of problems pointers were created to solve.
There are different problems pointer solve and are used for:
• Accessing array elements.
• Passing arguments to a function when the function needs to modify the original argument.
• Passing arrays and strings to functions.
• Obtaining memory from the system/Dynamic Memory Allocation.
• Creating data structures such as linked lists.
etc
2.16 Pointers and Arrays:
There is a close association between pointers and arrays.
Example:
#include <iostream>
using namespace std;
int main()
{
int intarray[5] = { 30, 40, 50, 60, 70 };
for(int j=0; j<5; j++) //for each element,
cout << intarray[j] << endl; //print value o/p:??
return 0;
}
Note: The size of an array has to be constant i.e. the size should be known at compile time.
i.e. int main()
{
int size;
cout<<‘‘Enter the size of an array‘‘;
cin>>size;
int myArray[size]; OUTPUT??
}
Solution:
DYNAMIC MEMORY ALLOCATION
2.19 Pointer Arithmetic:
As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic
operations on a pointer just as you can a numeric value.
ADDITION:
Ptr
myArray
0 1 2 3 4 5 6
TRY IT YOURSELF