Вы находитесь на странице: 1из 3

Programming Techniques Sheet #1 - Solution

CMP 103 & CMP N103 1/3 Spring 2014




1. Consider the following piece of code







Assume that the array "A" is stored at address 100 and the size of the int is 4 bytes.
Complete the following table:

Item Value Item Value
A 100
B 108
&A[0] 100
C 124
*A 1
C - B 4
A[0] 1
B[0] 20
*&A[0] 1
C[2] 80
&*A 100
*(B+1) 30
A[0]+7 8
*B+1 21
*(A+7) 70
*(&C[1]+1) 80
&A[2] 108
*&C[1]+1 71
&A[6] 124
*A**B**C 1200


2. What is the output of the following piece of code?
a.





Output:
100 0
104 1
108 2
112 3

3. What is the problem of the following pieces of code?
a.






Problem:
A = P; //Compilation error yes A is a pointer to int like P
//but A is a constant pointer cant change its value
Cairo University
Faculty of Engineering
Computer Engineering Department

Programming Techniques
Sheet #1 - Solution
int A[10] = {1, 10, 20, 30, 40, 50, 60, 70, 80, 90};
int *B;
int *C;
B = &A[2];
C = A+6;

int A[5] = {0, 1, 2, 3, 4};
int B[5] = {5, 6, 7, 8, 9};
int *P;
P=B;
A=P;
int A[5] = {0, 1, 2, 3, 4};
for(int* P=A; *P<4; P++)
cout<<P<<"\t"<<*P<<endl;
//Assume Array A is stored at address 100.
Programming Techniques Sheet #1 - Solution

CMP 103 & CMP N103 2/3 Spring 2014


b.







Problem:
Returning the address of an automatic variable. Pointer p
points to a memory location that will be free once the function exits.

c.














4. Write a function AlternateSplit that takes an array A of size n and splits it into two arrays B and
C. Your function should
a. Create two dynamic arrays B and C.
b. Copy elements from arrays A to B and C alternatively.
Note: don't use the notation Array_name[index] to copy array elements.
c. Free the array A.

void AlternateSplit(int* &A,int* &B,int* &C,int n)
{
int i,j;
//Dynamically allocate memory for B & C
B=new int[(n+1)/2]; // n+1 to account for odd values for n.
C=new int[n/2];

for(i=0,j=0; i<n/2; i++,j+=2)
{
*(B+i)=*(A+j); //Same as B[i] = A[j]
*(C+i)=*(A+j+1);//Same as C[i] = A[j+1]
}
if(j<n) //n is odd one element remaining
*(B+i) = *(A+j);//B[i] = A[j]

//Free Pointer A and set it to NULL
delete []A;
A=NULL;
}


int* f()
{
int =90;
int *p=&x;
return p;
}

1) int x, y;
2) !"n#t int $=30;
3) int * q;
4) int * const p = &x;
5) const int * r;
6) p = &y; can't change a const pointer
7) r = &y;
8) *% = 7;
9) *& = 9; r is a pointer to const (can't change pointee)
10) *' = 40; runtime error (q is not initialized, Bad Pointer)
11) $=(0; can't change a const variable
12) q = &z; q can't point to a const variable
13) r = &z;
Programming Techniques Sheet #1 - Solution

CMP 103 & CMP N103 3/3 Spring 2014

5. Write a function that swaps two dynamically allocated arrays (with equal sizes) but without
actually copying array elements from one place to another.

void SwapArr(int* &P, int* &R)
{
int *T = P;
P = R;
R = T;
}

Вам также может понравиться