Unit5 - Subjective Questions
CSE101 • Practice Questions with Detailed Answers
Define a Pointer in C programming. Explain the Indirection operator () and the Address-of operator () with a suitable example.
Definition: A pointer is a special variable that stores the memory address of another variable rather than a data value. It points to the location where the data is stored in memory.
Operators:
-
Address-of Operator ($\&`):
- It is a unary operator that returns the memory address of a variable.
- Example:
&xgives the address of variablex.
-
*Indirection (or Dereference) Operator ($`):**
- It is a unary operator used to access the value stored at the address a pointer is holding.
- Example:
*ptrgives the value stored at the address contained inptr.
Example:
c
int x = 10;
int *ptr;
ptr = &x; // ptr holds address of x
printf("Address of x: %p", ptr);
printf("Value of x: %d", *ptr); // Dereferencing
Explain the concept of Generic Pointers (Void Pointers). How do we dereference a void pointer?
Generic (Void) Pointer:
- A void pointer is a pointer that has no associated data type. It is declared using the keyword
void. - It can hold the address of any type of variable (int, char, float, etc.).
- Syntax:
void *ptr;
Dereferencing:
- A void pointer cannot be dereferenced directly because the compiler does not know the size of the data type it points to.
- It must be typecasted to the appropriate data type pointer before dereferencing.
Example:
c
int a = 10;
void ptr = &a;
printf("%d", (int)ptr); // Typecasting to int
Distinguish between a Dangling Pointer and a Wild Pointer with examples.
1. Wild Pointer:
- Definition: A pointer that has been declared but not initialized to point to any valid memory location is called a wild pointer. It points to a random (garbage) memory location.
- Example:
c
int p; // Wild pointer
p = 10; // Risky, might crash the program
2. Dangling Pointer:
- Definition: A pointer that points to a memory location that has been deleted (freed) or has gone out of scope.
- Causes:
- Deallocating memory using
free(). - Function returning the address of a local variable.
- Deallocating memory using
- Example:
c
int ptr = (int )malloc(sizeof(int));
free(ptr);
// ptr is now a dangling pointer
What is Pointer Arithmetic? Explain the rules for addition and subtraction operations on pointers with a diagrammatic representation or calculation.
Pointer Arithmetic:
Unlike normal arithmetic, pointer arithmetic depends on the data type the pointer points to. When we perform arithmetic operations, the address changes based on the size of the data type.
Rules:
- Increment/Addition: When we add an integer to a pointer, the address increases by .
- Formula:
- Decrement/Subtraction: When we subtract , the address decreases similarly.
- Subtraction of two pointers: Returns the number of elements between them (valid only if both point to the same array).
Example:
Assuming int is 4 bytes and ptr is at address 1000.
c
int ptr = 1000;
ptr = ptr + 2;
// New Address = 1000 + (2 4) = 1008
Explain how pointers are used to pass arguments to functions (Call by Reference). Write a C program to swap two numbers using pointers.
Call by Reference:
In this method, the address of the actual arguments is passed to the formal parameters. This allows the function to modify the actual variables in the calling function, as the function operates directly on memory addresses.
C Program to Swap Two Numbers:
c
include <stdio.h>
void swap(int x, int y) {
int temp;
temp = x; // Store value at address x in temp
x = y; // Copy value at address y to address x
y = temp; // Copy temp to address y
}
int main() {
int a = 10, b = 20;
printf("Before: a=%d, b=%d
", a, b);
swap(&a, &b); // Passing addresses
printf("After: a=%d, b=%d
", a, b);
return 0;
}
Output:
Before: a=10, b=20
After: a=20, b=10
Describe the relationship between Pointers and One-Dimensional Arrays. How can array elements be accessed using pointer notation?
Relationship:
- The name of an array represents the base address (address of the first element) of the array.
- It acts like a constant pointer.
- If
arris an array,arris equivalent to&arr[0].
Accessing Elements:
- Array Subscript Notation:
arr[i] - Pointer Notation:
*(arr + i)
Explanation:
arrpoints to index 0.arr + 1points to index 1.arr + ipoints to index .*(arr + i)retrieves the value at that address.
Example:
c
int arr[] = {10, 20, 30};
int ptr = arr;
printf("%d", (ptr + 1)); // Prints 20
What is a Null Pointer? How is it different from an uninitialized pointer? Why is it useful?
Null Pointer:
- A null pointer is a pointer that points to nothing. It is assigned the value
NULL(defined in<stdio.h>or<stddef.h>), which typically represents memory address 0. - Syntax:
int *ptr = NULL;
Difference from Uninitialized Pointer:
- Uninitialized (Wild): Contains a garbage address. Dereferencing it causes undefined behavior or crashes.
- Null: Explicitly states it points nowhere. It is safe to check against (e.g.,
if (ptr != NULL)).
Utility:
- To initialize a pointer when a valid address isn't available yet.
- To check if dynamic memory allocation (
malloc) was successful. - To mark the end of data structures like linked lists.
Compare Static Memory Allocation and Dynamic Memory Allocation. List the functions used for Dynamic Memory Management in C.
Comparison:
| Feature | Static Memory Allocation | Dynamic Memory Allocation |
|---|---|---|
| Time | Memory allocated at compile time. | Memory allocated at runtime. |
| Location | Stack memory. | Heap memory. |
| Size | Fixed; cannot be changed later. | Can be resized (using realloc). |
| Lifetime | Exists until the function returns. | Exists until explicitly freed. |
Dynamic Memory Functions (defined in <stdlib.h>):
malloc(): Allocates a block of memory.calloc(): Allocates contiguous blocks and initializes to zero.realloc(): Resizes previously allocated memory.free(): Deallocates memory.
Explain malloc() and calloc() with their syntax. Differentiate between them.
1. malloc() (Memory Allocation):
- Allocates a single large block of memory.
- Contains garbage values initially.
- Syntax:
void* malloc(size_t size); - Example:
ptr = (int*)malloc(5 * sizeof(int));
2. calloc() (Contiguous Allocation):
- Allocates multiple blocks of memory of the same size.
- Initializes all bytes to zero.
- Syntax:
void* calloc(size_t n, size_t size); - Example:
ptr = (int*)calloc(5, sizeof(int));
Differences:
- Initialization:
mallocleaves garbage values;callocinitializes to zero. - Arguments:
malloctakes 1 argument (total size);calloctakes 2 (number of elements, size of each).
What is the purpose of realloc() and free()? Explain the concept of a Memory Leak.
realloc():
- Used to change the size of the memory block pointed to by a previously allocated pointer (via malloc/calloc).
- Syntax:
void *realloc(void *ptr, size_t new_size); - It preserves the existing data while expanding or shrinking.
free():
- Releases the dynamically allocated memory back to the heap so it can be reused.
- Syntax:
void free(void *ptr); - Crucial to prevent memory leaks.
Memory Leak:
- Occurs when programmers create memory in the heap and forget to delete it (using
free()). - The memory remains occupied even though it's no longer needed, eventually exhausting available memory and causing system slowdowns or crashes.
How are Strings defined and initialized in C? Explain the significance of the Null Character (\0).
Definition:
In C, a string is a one-dimensional array of characters terminated by a null character (\0).
Initialization Methods:
- String Literal:
char str[] = "Hello";(Compiler adds\0automatically). - Character Array:
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};(Must explicitly add\0). - Pointer:
char *str = "Hello";(Stored in read-only memory).
Significance of Null Character (\0):
- It acts as a sentinel value indicating the end of the string.
- Functions like
printf,strlen, andstrcpyrely on\0to know where to stop processing. - Without it, functions would read adjacent memory until a crash occurs.
Discuss the different ways of reading a string from the user. Compare scanf() and gets()/fgets().
1. scanf("%s", str):
- Reads a string from input.
- Limitation: It terminates reading at the first whitespace (space, tab, newline). It cannot read multi-word strings like "Hello World".
2. gets(str) (Deprecated):
- Reads a line including spaces until a newline is found.
- Risk: Does not check array bounds, leading to buffer overflow attacks. Removed in C11.
3. fgets(str, size, stdin) (Recommended):
- Reads a line including spaces.
- Safety: Takes the maximum size as an argument, preventing buffer overflow.
- Note: It may include the newline character
at the end.
Comparison:
scanf is for single words; fgets is safe for sentences.
Explain Character Arithmetic with examples. How does C handle characters internally?
Internal Handling:
C treats characters as integers based on their ASCII values. For example, 'A' is 65, 'a' is 97, '0' is 48.
Character Arithmetic Operations:
Since they are stored as integers, we can perform arithmetic on them.
- Case Conversion:
- Lowercase to Uppercase:
'a' - 32->'A' - Uppercase to Lowercase:
'A' + 32->'a'
- Lowercase to Uppercase:
- Digit Character to Integer:
'5' - '0'results in the integer5.
- Next Character:
'A' + 1results in'B'.
Example:
c
char c = 'A';
printf("%d", c); // Prints 65
printf("%c", c + 1); // Prints 'B'
Write a C program (or function logic) to find the Length of a String without using the library function strlen().
Logic:
- Initialize a counter variable to 0.
- Loop through the character array.
- Continue the loop as long as the current character is not the null terminator (
\0). - Increment the counter in each iteration.
- Return the counter.
Code:
c
include <stdio.h>
int stringLength(char *str) {
int length = 0;
// Iterate until null terminator is found
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
char s[] = "Computer";
printf("Length: %d", stringLength(s));
return 0;
}
Explain the working of strcpy() and write a custom function to copy one string to another using pointers.
strcpy(dest, src):
It copies the content of the source string (src) (including the null terminator) to the destination buffer (dest). The destination array must be large enough to hold the source string.
Custom Implementation using Pointers:
c
include <stdio.h>
void myStrcpy(char dest, char src) {
// Loop while the value pointed by src is not null
while (src != '\0') {
dest = src; // Copy char from src to dest
src++; // Increment src pointer
dest++; // Increment dest pointer
}
dest = '\0'; // Explicitly append null terminator
}
int main() {
char source[] = "Source";
char destination[20];
myStrcpy(destination, source);
printf("Copied string: %s", destination);
return 0;
}
Write a C program to Concatenate two strings without using the strcat() library function.
Logic:
- Traverse the first string (destination) to find the null terminator (
\0). - Once the end of the first string is reached, start copying characters from the second string (source) to the destination.
- After copying the source, append
\0to the end.
Code:
c
include <stdio.h>
void myStrcat(char dest, char src) {
// 1. Move dest pointer to the end of the string
while (*dest != '\0') {
dest++;
}
// 2. Copy src to end of dest
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
// 3. Null terminate
*dest = '\0';
}
int main() {
char str1[50] = "Hello ";
char str2[] = "World";
myStrcat(str1, str2);
printf("%s", str1); // Output: Hello World
return 0;
}
Explain the logic behind the strcmp() function. What values does it return and why?
Logic:
strcmp(str1, str2) compares two strings character by character based on their ASCII values.
Process:
- It iterates through both strings simultaneously.
- If characters at the current index match, it moves to the next.
- The loop stops when a mismatch is found or
\0is reached.
Return Values:
- 0: If strings are identical (
str1 == str2). - Positive (> 0): If the ASCII value of the first unmatched character in
str1is greater than instr2(e.g., "Banana" vs "Apple"). - Negative (< 0): If the ASCII value in
str1is less than instr2(e.g., "Apple" vs "Banana").
Equation:
What is a Pointer to a Pointer (Double Pointer)? How is it declared and used? Give an example.
Definition:
A pointer to a pointer is a variable that stores the address of another pointer. It is used in dynamic memory allocation for multi-dimensional arrays or changing the address stored in a pointer within a function.
Declaration:
type **ptr_name;
Visual:
Variable Pointer 1 Pointer 2
Example:
c
int a = 10;
int *p1 = &a; // p1 holds address of a
int **p2 = &p1; // p2 holds address of p1
printf("%d", **p2);
// Dereference p2 -> gets p1.
// Dereference p1 -> gets a (10).
Explain the difference between an Array of Pointers and a Pointer to an Array with syntax and usage examples.
1. Array of Pointers:
- An array where each element is a pointer.
- Often used to store an array of strings.
- Syntax:
int *arr[5];(Array of 5 integer pointers). - Usage:
char *names[] = {"John", "Doe"};
2. Pointer to an Array:
- A single pointer that points to a whole array, not just the first element type.
- Syntax:
int (*ptr)[5];(Pointer to an array of 5 integers). - Usage: Used when passing 2D arrays to functions.
Key Syntax Difference:
*arr[5]vs(*ptr)[5](Parentheses make the difference).
Briefly describe the functionality of the following string library functions: strrev(), strlwr(), strupr(), and strncpy().
-
strrev(str):- Reverses the given string in place.
- Note: Non-standard function (available in some compilers like Turbo C, but not standard GCC).
-
strlwr(str):- Converts all uppercase characters in the string to lowercase.
- Note: Non-standard.
-
strupr(str):- Converts all lowercase characters in the string to uppercase.
- Note: Non-standard.
-
strncpy(dest, src, n):- Standard library function.
- Copies exactly
ncharacters fromsrctodest. - Safer than
strcpyas it prevents buffer overflows ifnis chosen correctly. Ifsrcis shorter thann, the rest is padded with null bytes.