1.3 Dynamic (Memory) Allocation in C++ Write the following functions in a C++ pr
ID: 3792301 • Letter: 1
Question
1.3 Dynamic (Memory) Allocation in C++
Write the following functions in a C++ program & save all of your code under the filename pointer_practice.cpp.
• Write a function, counter* make_broken_counter(), that creates a counter as a local variable and returns its address. Compile your program with all warnings enabled (-Wall for command line folks, otherwise look in compiler settings in your IDE). Note the warnings/errors.
• Write a function, void display_broken_counter (), that uses the function above to make a counter, increments and prints its count. Then have it call a few other functions (doesn’t matter what functions as long as they some local variables), then try to increment the counter and print its count again. Call this function from your main. What happens?
• Write a function, counter* make_counter(), that creates a counter using new and returns the resulting pointer.
• Write a function, void display_counter (), that uses the function above to make a counter, increments and prints its count. Then have it call a few other functions (doesn’t matter what functions as long as they some local variables), then try to increment the counter and print its count again. Call this function from your main. What happens?
• Write a function, counter* make_counter (int start), that creates a counter using new, passing start to its constructor, and returns the resulting pointer.
• Write a function, void display_counter_2 (), that calls this function and displays the resulting counter’s count. Modify main to call this function...
• Write a function, counter* bunch_of_counters (size_t number), that uses new to create an array of number counters. Return the base pointer of the array.
• Write a function, void display_counters (), that uses the function above to make an array of 25 counters, increments them each 5 times and then prints each of their counts.Modify main to call this function.
Explanation / Answer
#include<iostream.h>
#include<conio.h>
void main()
{
int *ptr=new int(25);
float *pt1=new float(12.98);
char *ptr2=new char('f');
clrscr();
cout<<"Integer value is "<<*ptr<<endl;
cout<<"Float value is "<<*pt1<<endl;
cout<<"Char value is "<<*ptr2;
getch();
delete ptr;
cout<<endl;
cout<<*ptr;
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.