شرح + اسئله لموضوع Pointers في لغة c++
Lab 2: Using Pointers
Lab Objectives:
In this lab students will learn:
ü Memory concept of variables, pointers and how to use variable identifiers and pointers to refer to the variable.
ü Pointer variable declarations and initialization.
ü Direct and indirect referencing a variable using the pointer operators.
ü Using * and address (&) operators.
Background:
When declaring a variable, it is located at a specific location in memory, the memory address. The task of locating variables is automatically performed by the operating system during runtime. In some cases we need to know the address where the variable is being stored during runtime.
Variable which stores a reference to another variable is called a pointer. We can directly access the value stored in the variable using a pointer which points to it.
Syntax:
1. Pointer Declaration:
Syntax: Pointer_type *Pointer_name;
Example: int *Ptr1; double *Ptr2;
2. Pointer initialization:
Syntax: Pointer_name=NULL;
Pointer_name=&variable_name;
Example: int *Ptr1, var;
Ptr1=&var;
3. Example: Write a c++ program that defines an integer variable var1 and a pointer Ptr that points to var1. Assign and print value to var1, then assign and print a new value to var1 using Ptr.
Solution:
#include<iostream>
using namespace std;
void main()
{
int var1,*ptr;
ptr=&var1;
var1=10;
cout<<var1;
cout<<endl;
*ptr=20;
cout<<*ptr;
}
Lab Problems:
Lab Problem-1: Explain the error.
char c = 'A';
double *p = &c;
Lab Problem-2: Consider the following statements:
int *p;
int i;
int k;
i = 42;
k = i;
p = &i;
After these statements, which of the following statements will change the value of i to 75?
A. k = 75;
B. *k = 75;
C. p = 75;
D. *p = 75;
Lab Problem-3:: Introduce int variables x and y and int* pointer variables p and q. Set x to 2, y to 8, p to the address of x, and q to the address of y. Then print the following information:
(1) The address of x and the value of x.
(2) The value of p and the value of *p.
(3) The address of y and the value of y.
(4) The value of q and the value of *q.
(5) The address of p (not its contents!).
(6) The address of q (not its contents!).
Lab Problem-4: Write a function countEven(int*, int) which receives an integer array and its size, and returns the number of even numbers in the array.
حلو
ردحذف