Question: (C++) 3.How can you use pointer to print the first element of an array? Give an example. 4.Explain the Program Output listed on page 507,

(C++)

3.How can you use pointer to print the first element of an array? Give an example.

4.Explain the Program Output listed on page 507, Program9-7 of the text book. How does the pointer notation work with array name?

PAGE 507 PROGRAM 9-7:

 1 // This program uses subscript notation with a pointer variable and 2 // pointer notation with an array name. 3 #include  4 #include  5 using namespace std; 6 7 int main() 8 { 9 const int NUM_COINS = 5; 10 double coins[NUM_COINS] = {0.05, 0.1, 0.25, 0.5, 1.0}; 11 double *doublePtr; // Pointer to a double 12 int count; // Array index 13 14 // Assign the address of the coins array to doublePtr. 15 doublePtr = coins; 16 17 // Display the contents of the coins array. Use subscripts 18 // with the pointer! 19 cout << "Here are the values in the coins array: "; 20 for (count = 0; count < NUM_COINS; count++) 21 cout << doublePtr[count] << " "; 22 23 // Display the contents of the array again, but this time 24 // use pointer notation with the array name! 25 cout << " And here they are again: "; 26 for (count = 0; count < NUM_COINS; count++) 27 cout << *(coins + count) << " "; 28 cout << endl; 29 return 0; 30 } 

Program Output

Here are the values in the coins array: 0.05 0.1 0.25 0.5 1 And here they are again: 0.05 0.1 0.25 0.5 1 

Note on Question 3 and 4 above: It is very critical that you thoroughly understand the use of pointers to access elements of an array. This is a very common use case.

5.When you increment/decrement a pointer, are you changing the address or the element at the address? If it is the address, how does the program now how much to increment or decrement? Hint: Remember the use of sizeof function in earlier chapters.

6.Explain the difference between the following; assuming ptr1 and ptr2 are pointers to integers.

If (ptr1 < ptr2)

If (*ptr1 < *ptr2)

7.

a.Why do we need dynamic memory allocation?

b.What commands are used to allocate and release memory?

c. What is memory leak, and how do you prevent it?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!