1. Provide an example of how you would use a pointer in a program. Explain an ad
ID: 3641125 • Letter: 1
Question
1. Provide an example of how you would use a pointer in a program. Explain an advantage of using a pointer versus using a nonpointer variable.2. a pointer variables holds the address of a value (in memory), so:
int x
is different than:
int *x;
Ok, if I want the pointer *x to point to the value 2, how can I do that? What's the C++ instruction that assigns the value 2 to the memory location *x is pointing to?
3. Describe a situation where dynamic memory allocation might be required in order to make efficient use of your computer's resources.
4. Also describe the precautions that your program should take for the correct and efficient implementation of dynamic memory allocation.
Explanation / Answer
1. An array pointer is very common, or a pointer to a data structure such as List. An advantage of pointer is that you don't need to copy the whole data structure to pass it to a method and you are working on one, mutable piece of data. 2. Well, pointer can only point to a VARIABLE, not a value. value must be sotred somewhere first. so you can do sth like: int x = 2; int * ptr = &x; now ptr points to value 2. we can now modify the value of the cell we point to by: *ptr = 100; now we point to a 100! 3. Well, in any program you need to allocate objects on-the-fly. In some cases you could scan through the code and see how many objects you have, but there are indeterministic programs such as "ask user for a number and create X Bicycle objects" that cannot be preallocated, unless you preallocate enough for ANY X, but that might be wasteful and inefficient. Besides, you want to clean up the memory as well, so deallocation is also an issue here. 4. Precautions: efficient data structure to store available space, allow deallocation (garbage collection?) mechanism, allow compaction, allow bounds checking, allow statistics (how much space we are using, should we release some of earlier objects for the sake of new ones coming in etc.) hope the above helps.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.