Unit 2: Handling Pointers, Arrays and String - Subjective Questions
CAP455 — Object Oriented Programming Using C++ • Practice Questions with Detailed Answers
20 questions
Explain the differences between pointer variables and reference variables in C++.
Pointer variables and reference variables both provide indirect access to data, but they differ in several ways:
- A pointer stores the memory address of another variable and is declared using
*, for example,int *p;. - A reference is an alias for an existing variable and is declared using
&, for example,int &r = x;. - A pointer can be reassigned to point to another object, whereas a reference normally cannot be reseated after initialization.
- A pointer can contain
nullptr, but a reference must refer to a valid object when it is created. - Pointers require dereferencing using
*p, while references are used like ordinary variables. - Pointer arithmetic is allowed, but arithmetic on references is not allowed.
Example: int x = 10; int *p = &x; int &r = x;. Here, p stores the address of x, while r is another name for x.
What is a void pointer? Explain its declaration, use, and limitations with an example.
A void pointer is a pointer that can store the address of an object of any data type. It is declared using void *.
Example:
int x = 25; void *ptr = &x;
The pointer ptr can hold the address of x, but it cannot be dereferenced directly because the compiler does not know the data type or size of the object. It must first be converted to the correct pointer type:
cout << *static_cast<int *>(ptr);
Important points:
- A void pointer can store addresses of different data types.
- It cannot be dereferenced directly.
- Pointer arithmetic on a standard
void *is not allowed because its pointed-to type has no known size. - Correct type conversion is necessary before accessing the stored value.
- It is useful in generic programming and memory-management functions.
Explain pointer arithmetic in C++. Derive the addresses obtained when an integer pointer is incremented.
Pointer arithmetic operates according to the size of the data type to which a pointer points. If p is an int *, then p + 1 advances the pointer by sizeof(int) bytes rather than by one byte.
Suppose p contains address and `sizeof(int) = 4$ bytes. Then:
prefers to address .p + 1refers to address .p + 2refers to address .p - 1refers to address .
Commonly permitted operations include:
- Incrementing and decrementing a pointer.
- Adding or subtracting an integer from a pointer.
- Subtracting two pointers belonging to the same array.
- Comparing pointers belonging to the same array.
Pointer arithmetic is mainly used for traversing arrays. It must not be used to access memory outside the valid array range.
What is a pointer to pointer? Explain its declaration and use with a suitable C++ example.
A pointer to pointer is a pointer that stores the address of another pointer. It is declared using two asterisks, such as int **pp.
Example:
int x = 50;
int *p = &x;
int **pp = &p;
Here:
xstores the value50.pstores the address ofx.ppstores the address ofp.*ppgives the value ofp, which is the address ofx.**ppgives the value ofx, which is50.
Pointer-to-pointer variables are useful for modifying a pointer inside a function, representing dynamically allocated two-dimensional arrays, and handling arrays of character pointers.
Define dangling pointer, wild pointer, and null pointer. Distinguish among them and explain how each can be avoided.
Dangling pointer: A pointer that refers to memory whose object has already been destroyed or deallocated. It can be avoided by assigning nullptr after delete and by not returning the address of a local variable.
Wild pointer: An uninitialized pointer containing an unpredictable address. For example, int *p; creates a wild pointer. It can be avoided by initializing pointers, such as int *p = nullptr;.
Null pointer: A pointer that intentionally represents no valid object. It can be declared as int *p = nullptr;.
Comparison:
- A wild pointer has an indeterminate address.
- A dangling pointer once pointed to a valid object, but that object is no longer available.
- A null pointer points to no object by design.
Dereferencing wild or dangling pointers causes undefined behavior. A null pointer must also not be dereferenced.
Explain null pointer assignment in modern C++. Why is nullptr preferred over 0 and NULL?
A null pointer is a pointer that does not point to any valid object. In modern C++, it should be assigned using the keyword nullptr:
int *p = nullptr;
Before C++11, programmers commonly used 0 or NULL. However, nullptr is preferred because it has a dedicated type, std::nullptr_t, and is not treated as an integer.
For example, overloaded functions can produce ambiguity with NULL:
void test(int);
void test(int *);
Using test(nullptr) selects the pointer version clearly. Important safety rules include:
- Test a pointer before dereferencing it.
- Set a pointer to
nullptrafter releasing its dynamically allocated memory. - Do not confuse a null pointer with an uninitialized pointer.
- Never perform
*pwhenp == nullptr.
Describe how pointers can be declared as class data members. Explain their initialization and memory-management requirements.
A class can contain pointer data members to store addresses of dynamically allocated or externally managed objects.
Example:
class Sample {
int *value;
public:
Sample(int n) : value(new int(n)) {}
~Sample() { delete value; }
};
Important considerations:
- A pointer data member should be initialized in the constructor, preferably through a member-initializer list.
- If the class owns dynamically allocated memory, its destructor must release that memory.
- The copy constructor and copy-assignment operator may need to be defined to perform a deep copy.
- A pointer member may also be initialized to
nullptrwhen it does not own an object. - Double deletion and memory leaks must be prevented.
Modern C++ generally prefers smart pointers such as std::unique_ptr for automatic ownership management.
Explain pointers to objects in C++ with syntax for object creation, member access, and dynamic allocation.
A pointer to an object stores the address of an object. The arrow operator -> is used to access members through the pointer.
Example:
class Student {
public:
void display() { cout << "Student"; }
};
Student s;
Student *p = &s;
p->display();
The expression p->display() is equivalent to (*p).display().
An object can also be created dynamically:
Student *q = new Student;
q->display();
delete q;
The delete operation is necessary for memory allocated using new. After deletion, the pointer should preferably be assigned nullptr to avoid becoming a dangling pointer.
What is the this pointer? Explain its characteristics and uses inside a class.
The this pointer is an implicit pointer available inside non-static member functions. It points to the object that invoked the function.
Example:
class Account {
int balance;
public:
void setBalance(int balance) {
this->balance = balance;
}
};
The this pointer is useful when a parameter and a data member have the same name, for returning the current object, and for passing the current object to another function.
Important characteristics:
- It is available only in non-static member functions.
- It cannot be used directly in a static member function.
- It is a pointer to the current object.
this->memberaccesses a member of the current object.- A member function may return
*thisto support method chaining.
Explain a pointer to a data member in C++. Give its declaration and demonstrate how it is used.
A pointer to a data member stores the location of a non-static data member relative to objects of a particular class. It is declared using the syntax data_type ClassName::*.
Example:
class Student {
public:
int marks;
};
int Student::*ptr = &Student::marks;
Student s;
s.*ptr = 90;
For an object pointer, the member is accessed using the ->* operator:
Student *p = &s;
p->*ptr = 95;
The operators used are:
object.*pointer_to_memberobject_pointer->*pointer_to_member
A pointer to a data member is different from an ordinary pointer because it does not contain a normal standalone memory address. It identifies a member within objects of a particular class.
Explain the declaration, initialization, and processing of one-dimensional and multidimensional arrays in the main() function.
An array stores multiple values of the same type in contiguous memory locations. A one-dimensional array is declared as:
int marks[5] = {70, 80, 65, 90, 85};
Its elements are accessed using indices from to :
cout << marks[2];
A two-dimensional array is declared as:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
It can be processed using nested loops:
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << matrix[i][j];
}
}
The first index identifies the row and the second identifies the column. C++ stores multidimensional arrays in row-major order, meaning the elements of each row are stored consecutively.
Describe how a multidimensional array can be declared and processed inside a class.
A multidimensional array can be declared as a private or public data member of a class and processed through member functions.
Example:
class Matrix {
int a[2][3];
public:
void input() {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
cin >> a[i][j];
}
void display() {
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j)
cout << a[i][j] << " ";
cout << endl;
}
}
};
The array belongs to each object of the class. Member functions provide controlled access and can perform operations such as displaying, addition, transposition, or searching.
Explain row-major storage of a two-dimensional C++ array and derive the address formula for an element.
C++ stores a two-dimensional array in row-major order. This means all elements of the first row are stored first, followed by all elements of the second row, and so on.
For an array declared as A[R][C], assuming zero-based indexing, the address of A[i][j] is:
where:
Baseis the address ofA[0][0].Cis the number of columns.Tis the element type.iis the row index.jis the column index.
For example, if an array has columns, the linear position of A[2][1] is:
Thus, the element is the tenth item when counting from position zero. This arrangement allows efficient traversal when the inner loop processes columns.
What is an array of objects? Explain its declaration, initialization, and processing with an example.
An array of objects is an array whose elements are objects of the same class. It is useful when several objects with identical structure must be managed together.
Example:
class Student {
public:
int roll;
void display() { cout << roll << endl; }
};
Student students[3];
Each object can be accessed using an index:
students[0].roll = 1;
students[1].roll = 2;
for (int i = 0; i < 3; ++i) {
students[i].display();
}
If a class has constructors, the appropriate constructor is called for every array element. An array of objects can be used for student records, employee details, inventory items, or bank accounts.
Explain the standard C++ string class and compare it with a traditional character array.
The standard C++ string class is provided by the <string> header and belongs to the std namespace. It represents a sequence of characters and manages its own memory.
Example:
#include <string>
std::string name = "Alice";
Advantages over a character array include:
- Dynamic size management.
- Direct assignment and copying.
- Convenient concatenation using
+or+=. - Built-in comparison operators.
- Member functions such as
length(),substr(),find(), andreplace(). - No need for a terminating null character to be managed explicitly by the programmer.
A character array such as char name[20] has fixed storage and requires functions such as strcpy() and strlen(). The string class is generally safer and easier to use.
Describe different ways of defining and assigning string objects in C++.
String objects can be defined and assigned in several ways.
- Default construction:
std::string s1;creates an empty string. - Initialization with a string literal:
std::string s2 = "C++";. - Direct initialization:
std::string s3("Programming");. - Copy initialization:
std::string s4 = s3;. - Assignment after declaration:
s1 = "Learning";. - Assignment from another string object:
s1 = s3;. - Construction from a character array:
char text[] = "Hello"; std::string s5(text);.
Strings can also be combined:
std::string full = first + " " + last;
The assignment operator automatically replaces the previous contents of the destination string. The clear() member function can be used to remove all characters, and empty() can test whether the string contains no characters.
Explain the important modifiers of the C++ string class, such as append, insert, erase, replace, and clear.
String modifiers change the contents of a std::string object.
append(): Adds characters at the end. Example:s.append(" World");.operator+=: Appends another string or character sequence. Example:s += "!";.insert(): Inserts characters at a specified position. Example:s.insert(5, " C++");.erase(): Removes characters from a specified position. Example:s.erase(5, 4);removes four characters beginning at index .replace(): Replaces a portion of the string. Example:s.replace(0, 5, "Hi");.clear(): Removes all characters from the string.resize(): Changes the number of characters in the string.swap(): Exchanges the contents of two strings.
Indexes are zero-based. Programs should use valid positions and lengths to avoid exceptions or unexpected results.
Explain commonly used non-modifying operations of the C++ string class, including length, comparison, searching, and substring extraction.
Several std::string functions inspect or extract data without directly changing the original string.
length()andsize()return the number of characters.empty()returnstrueif the string has no characters.at(index)accesses a character with bounds checking.operator[]accesses a character without bounds checking.compare()compares two strings lexicographically.find()searches for the first occurrence of a substring or character.rfind()searches from the end.substr(pos, count)returns a substring beginning atpos.front()andback()access the first and last characters.
Example:
std::string s = "Object Oriented";
size_t position = s.find("Oriented");
std::string part = s.substr(0, 6);
If find() fails, it returns std::string::npos.
Compare static arrays and dynamically allocated arrays in C++. Discuss their memory allocation, size, and deallocation.
A static or automatic array is declared with a fixed size known at compile time, for example, int a[10];. Its storage is managed automatically according to its scope.
A dynamically allocated array obtains storage at runtime:
int n; cin >> n;
int *a = new int[n];
delete[] a;
Comparison:
- Static array size is fixed, while dynamic array size can be selected at runtime.
- Static arrays are automatically destroyed when their scope ends.
- Dynamic arrays require explicit release using
delete[]. - Forgetting
delete[]causes a memory leak. - Using
deleteinstead ofdelete[]for an array produces undefined behavior. - Modern C++ often prefers
std::vectorbecause it manages dynamic storage automatically.
The pointer used for a dynamic array should not be dereferenced after delete[] and should preferably be set to nullptr.
Explain how pointers and arrays are related in C++. Include array traversal using pointer arithmetic and state important differences.
In many expressions, the name of an array decays into a pointer to its first element. For an array int a[4], the expression a generally represents &a[0].
Example:
int a[4] = {10, 20, 30, 40};
int *p = a;
cout << *(p + 2);
The expression *(p + 2) accesses the third element, a[2]. A loop can traverse the array as follows:
for (int *q = a; q != a + 4; ++q) {
cout << *q;
}
Differences:
- An array has fixed storage for its elements, whereas a pointer is a separate variable storing an address.
- An array name cannot be assigned a new address, but a pointer can be reassigned.
sizeof(a)gives the total array size in the same scope, whilesizeof(p)gives the pointer size.- An array passed to a function usually becomes a pointer to its first element.
Explain the differences between pointer variables and reference variables in C++.
Pointer variables and reference variables both provide indirect access to data, but they differ in several ways:
- A pointer stores the memory address of another variable and is declared using
*, for example,int *p;. - A reference is an alias for an existing variable and is declared using
&, for example,int &r = x;. - A pointer can be reassigned to point to another object, whereas a reference normally cannot be reseated after initialization.
- A pointer can contain
nullptr, but a reference must refer to a valid object when it is created. - Pointers require dereferencing using
*p, while references are used like ordinary variables. - Pointer arithmetic is allowed, but arithmetic on references is not allowed.
Example: int x = 10; int *p = &x; int &r = x;. Here, p stores the address of x, while r is another name for x.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →