Professional Documents
Culture Documents
Pointers: - Pointers and Arrays - Pointers and Structures - Pointers and Functions (Call by Address)
Pointers: - Pointers and Arrays - Pointers and Structures - Pointers and Functions (Call by Address)
Now…
Quantity = 50;//assigns 50 to Quantity
*p = 50; //assigns 50 to Quantity
p=&x[0];
void main() {
int *p, sum=0, j, i=0;
int x[5] ={5, 9, 6,3,7};
p=x;
while(i<5){ Output:
sum+=*p;
Sum of
i++; elements =30
p++; }
cout<<“sum of elements =“<<sum;
}
10/9/19 Department of CSE 13
Dynamic array
#include <iostream>
#include <new>
using namespace std;
int main ()
{ int i,n; int * p;
cout << "How many numbers would you like to type? "; cin >> n;
p= new int[n];
for (i=0; i<n; i++)
{ cout << "Enter number: ";
cin >> p[i]; }
cout << "You have entered: ";
for (i=0; i<n; i++)
cout << p[i] << ", ";
delete[] p;
return 0; }
10/9/19 Department of CSE 14
How many numbers would you like to type? 5
Enter number : 75
Enter number : 436
Enter number : 1067
Enter number : 8
Enter number : 32
You have entered: 75, 436, 1067, 8, 32,
*p = *p + 10 ; cout<<“x after
} change:-”<< x;
}
10/9/19 Department of CSE 16
Function returning pointer
A function can return single value by its name or return multiple
values through pointer parameters.
int *larger (int *x,
int *larger (int *, int
*); int *y)
void main() {
{
if (*x > *y)
int a=10, b=20, *p;
return (x);
p=larger (&a, &b);
else
cout<<*p; return(y);
}
}
10/9/19 Department of CSE 18
Pointers and Structures- example
struct invent
{ void main()
char name[30];{
int number; struct invent prod[3], *ptr;
float price; for(ptr = prod; ptr < prod+3; ptr++)
}; cin>>ptr name>>ptr number>>ptr
price;
ptr=prod;
When ptr is incremented by one, it points to the next record. i.e. product[1]