Adv.c Question Bank
Adv.c Question Bank
A user-defined data type that allows you to store different data types in same memory location.
What is pointer?
A variable that stores the memory address of another variable, allowing you to directly access and manipulate data
stored in that memory location.
Strlen().
Text files, Binary files, Source code files, Header files, Object files,
Row_index , colum_index
Define macro.
A macro is a preprocessor directive that allows you to define a shortcut or an alias for a piece of code.
union.
Used to reset the file pointer to the beginning of a file, allowing you to read the file from the start again.
Define string.
What is pointer ?
Example :
#include <stdio.h>
int main() {
char myString[] = "Hello, world!"; // String literal
char anotherString[20] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Character array with null terminator
printf("%s\n", myString); // Prints "Hello, world!"
printf("%s\n", anotherString); // Prints "Hello"
return 0;
}
Define function.
A function is a block of code that performs a specific task and can be called multiple times from different parts of a
program.
To declare a pointer variable, you use an asterisk (*) before the variable name, indicating it will store a memory
address. Initialization involves assigning a valid memory address to the pointer, typically using the address-of
operator (&).
Here's a breakdown:
1. Declaration:
Syntax: data_type *pointer_name;
Example: int *ptr; (declares a pointer named ptr that can store the address of an integer)
Explanation:
data_type specifies the type of data the pointer will point to (e.g., int, float, char).
* indicates that the variable is a pointer.
pointer_name is the name you choose for the pointer variable.
2. Initialization:
Syntax: pointer_name = &variable;
Example: int num = 10; int *ptr = # (declares an integer num, then declares a pointer ptr and initializes it with
the address of num)
Explanation:
&variable is the address-of operator, which returns the memory address of the variable.
pointer_name = &variable; assigns the address of variable to the pointer pointer_name.
Allows you to allocate memory during program execution, rather than at compile time.
You can also initialize the array with values when you declare it:
int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Define preprocessor.
A program that processes the source code before it’s compiled, performing tasks like including files, defining
macros, and conditionally compiling code.
Dynamic array size allocation can be done using memory allocation functions such as malloc(), calloc(), or relloc().
Allow the preprocessor to replace identifiers(macro names)with specified text before compilation, enabling code
reusability and flexibility.
Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).
Opening an existing file (fopen).
Reading from file (fscanf or fgets).
Writing to a file (fprintf or fputs).
Moving to a specific location in a file (fseek, rewind).
Closing a file (fclose).
* (Dereference Operator):
The * operator is used to access the value stored at a memory address.
Syntax:
*pointer_name.
Initialization:
After declaration, you need to initialize the pointer with a valid memory address.
Using the address-of operator (&): You can obtain the address of a variable using the & operator and assign it to the
pointer.
int num = 10; declares an integer variable num.
int *ptr = # declares a pointer ptr and initializes it to point to the memory address of num.
Using malloc (Dynamic Memory Allocation): You can allocate memory dynamically using malloc and assign the
returned address to the pointer.
int *ptr = (int *)malloc(sizeof(int)); allocates enough memory for an integer and assigns the address to ptr.
Initializing to NULL: You can also initialize a pointer to NULL, which means it doesn't point to any valid memory
location.
int *ptr = NULL;
Arrays are classified primarily as one-dimensional (1D) and multi-dimensional (2D, 3D, etc.), with 1D arrays storing
elements in a linear sequence and multi-dimensional arrays representing data in tables or matrices.
Here's a more detailed explanation:
1. One-Dimensional Arrays (1D):
Definition: A 1D array is a simple collection of elements of the same data type, stored contiguously in memory,
accessed using a single index (starting from 0).
Example: int numbers[5] = {10, 20, 30, 40, 50};
Accessing elements: numbers[0] will access the first element (10), numbers[2] will access the third element (30).
2. Multi-Dimensional Arrays (2D, 3D, etc.):
Definition:
These arrays have more than one dimension, allowing for storing data in a tabular or matrix format.
2D Arrays:
Represented as rows and columns, like a table or matrix.
Example: int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
Accessing elements: matrix[0][0] will access the element in the first row and first column (1), matrix[1][2] will access
the element in the second row and third column (7).
3. 3D Arrays (and beyond):
Can be thought of as an array of 2D arrays, or an array of arrays of arrays, and so on.
Example: `int cube = {{{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}}; `
Accessing elements: cube[0][1][0] will access the element in the first cube, second row, first column (5).
Structures in C offer several advantages, including organizing data of different types, improving code readability
and maintainability, facilitating the creation of custom data types, and enabling efficient data manipulation and
passing to functions.
Here's a more detailed breakdown of the advantages:
Organizing Heterogeneous Data:
Structures allow you to group different data types (integers, floats, characters, etc.) under a single name, making it
easier to manage related data as a unit.
Improved Code Readability and Maintainability:
By using structures, you can create meaningful data types that represent real-world entities, making your code
easier to understand and maintain.
Custom Data Types:
Structures enable you to define your own data types, which can be used to represent complex data structures or
objects, extending the capabilities of the language.
Efficient Data Manipulation:
You can access and modify individual members of a structure using the dot operator (variable.member), making it
easy to work with the data stored within.
Simplified Parameter Passing:
Structures can be passed to functions as a single parameter, representing a group of related values, which can
simplify function design and reduce the number of arguments needed.
Arrays of Structures:
You can create arrays of structures, allowing you to store and manage multiple instances of the same data type
efficiently.
Data Abstraction:
Structures can hide the implementation details of data, allowing you to focus on the data's logical structure rather
than its physical representation.
Code Reusability:
Structures can be reused as templates for representing similar types of data, reducing redundancy in your code and
promoting a consistent data structure.
instructs the preprocessor to insert the contents of a specified file into the source code at the point where the
directive appears.
Example:
int *ptr; // declares a pointer to an integer
char *name; // declares a pointer to a character
float *balance; // declares a pointer to a floating-point number
```
```
struct Person {
int age;
char name[20];
};
c
struct Person {
int age;
char name[20];
};
The strcmp() function in C compares two strings lexicographically (character by character) and returns an integer
indicating their relationship: 0 if they are equal, a negative value if the first string is lexicographically less than the
second, and a positive value otherwise.
Example:
#include <stdio.h>
#include <string.h>
int main(){
char* s1 = "Geeks";
char* s2 = "Geeks";
return 0;
}
• fopen()
• fputs()
• fclose()
• fseek()
i) fopen():
• Purpose: The fopen() function is used to open a file for reading, writing, or both.
o mode: A string specifying the mode in which the file should be opened (e.g., "r" for read, "w" for
write, "a" for append, "r+" for read and write, etc.).
iii) fclose():
iv) fseek():
• Purpose: The fseek() function changes the position of the file pointer (or stream) within a file.
o origin: Specifies the starting point for the offset (e.g., SEEK_SET for the beginning, SEEK_CUR for the
current position, SEEK_END for the end).
• scanf():
• Reads input from the standard input stream (usually the keyboard).
• Uses format specifiers (like %d, %f, %s) to determine the data type of the input and how to store it.
• Stops reading input when it encounters whitespace characters (spaces, tabs, or newlines).
• Reads a line of text from the standard input stream until a newline character is encountered.
• Important: gets() is unsafe because it doesn't check the size of the input buffer, potentially leading to
buffer overflows if the input is longer than the buffer.
• Deprecated: Due to the security risks, gets() is now discouraged and often replaced with fgets().
• Example: gets(my_string);
Macro substitution directives in C are a powerful feature of the C preprocessor, a tool that processes your source
code before it is compiled. These directives allow you to define macros, essentially shortcuts or replacements for
code snippets. When the program is compiled, all instances of the macro are replaced by its defined contents.
#include <stdio.h>
void main ()
int num[20];
int i, j, a, n;
scanf("%d", &n);
scanf("%d", &num[i]);
a = num[i];
num[i] = num[j];
num[j] = a;
}
printf("%d", num[i]);
getch();
create a structure of car having car_iD, car_moDel, price. anD accept the Details of
tWo car anD Display it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct Car{
int id:
char model [20];
int rate;
};
void main()
{
int n,i;
printf("Enter the number of cars: ");
scanf("%d",&n);
Structures allow you to store multiple data types simultaneously, which is crucial for organizing complex data.
• Independent Data:
Each member in a structure has its own memory location, ensuring that changes to one member do not affect
others.
• Data Integrity:
Structures are better suited for applications where data integrity and consistency are paramount.
• Code Readability:
Structures enhance code readability by grouping related data items under a single name, making it easier to
understand and maintain.
• General Purpose:
Structures are more versatile and suitable for a wider range of applications compared to unions.
A structure is a user-defined data type that A union is a user-defined data type that allows
groups different data types into a single storing different data types at the same memory
Definition entity. location.
The size is the sum of the sizes of all The size is equal to the size of the largest member,
Size members, with padding if necessary. with possible padding.
Memory Each member within a structure is allocated Memory allocated is shared by individual members
Allocation unique storage area of location. of union.
Data No data overlap as members are Full data overlap as members shares the same
Overlap independent. memory.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5], n, sum=0, i;
float avg=0;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements in the array: ");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nSum of the elements in the array is: ");
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("%d",sum);
printf("\nAverage of the elements in the array is: ");
for(i=0;i<n;i++)
{
avg=sum/n;
}
printf("%f",avg);
getch();
}
create a structure stuDent having rno, name, aDDress. accept the Details of tWo
stuDent anD Display it.
#include <stdio.h>
void main() {
// Declare two struct Student variables
struct Student student1, student2;
printf("\nStudent 2:\n");
printf("Roll Number: %d\n", student2.rollNumber);
printf("Name: %s\n", student2.name);
printf("Address: %s\n", student2.address);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int length;
char str[50];
printf("Enter the string: ");
scanf("%s",&str);
length=strlen(str);
printf("Length of the string is: %d",length);
getch();
}
#include <stdio.h>
// Define PI as a macro
#define PI 3.14159
void main() {
float radius, area;
getch();
}
Write a c program to combine tWo string using stanDarD function.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50],str2[50];
printf("Enter the string 1: ");
scanf("%s",&str);
printf("Enter the string 2: ");
scanf("%s",&str2);
strcat(str,str2);
printf("Combined string is : %s",str);
getch();
}
#include <stdio.h>
int main() {
int matrix1[10][10], matrix2[10][10], result[10][10];
int row, col;
return 0;
}
Write a c program to combine tWo string using stanDarD function.
#include <stdio.h>
#include <string.h>
Void main() {
char str1[100], str2[100], result[200];
getch();
}
Write a program to Display aDDition of matrix.
#include <stdio.h>
#define ROWS 2
#define COLS 2
int main() {
int matrix1[ROWS][COLS] = {{1, 2}, {3, 4}};
int matrix2[ROWS][COLS] = {{5, 6}, {7, 8}};
int result[ROWS][COLS];
printf("Matrix 1:\n");
displayMatrix(matrix1);
printf("Matrix 2:\n");
displayMatrix(matrix2);
printf("Result:\n");
displayMatrix(result);
return 0;
}
explain aDvantages anD DisaDvantages of pointer.
Advantages of Pointers:
1. Dynamic Memory Allocation: Pointers allow for dynamic memory allocation, enabling efficient memory
usage and adaptability.
2. Efficient Data Structures: Pointers facilitate the creation of complex data structures like linked lists, trees,
and graphs, which can be memory-efficient and flexible.
3. Function Parameter Passing: Passing pointers to functions can be more efficient than passing large data
structures by value in terms of memory and execution speed.
4. Manipulating Hardware and System Resources: Pointers are essential for low-level system programming,
device driver development, and interacting with hardware, providing direct memory access.
5. String Manipulation: C-style strings (character arrays) rely on pointers for efficient manipulation and
processing, making them a core feature of string handling in C.
Disadvantages of Pointers:
1. Complexity: Pointers introduce complexity and can make code harder to understand and debug, especially
for novice programmers.
2. Dangling Pointers: Dangling pointers can point to deallocated or invalid memory, leading to unpredictable
behavior.
3. Memory Leaks: Improper management of dynamically allocated memory can result in memory leaks,
consuming more memory over time.
4. Security Risks: Improper pointer usage can introduce security vulnerabilities such as buffer overflows,
compromising program security.
5. Platform Dependence: Pointer behavior can vary across platforms and compilers, making code less portable.
6. Debugging Challenges: Debugging pointer-related issues can be challenging, as errors may not manifest
immediately and can lead to subtle, hard-to-track bugs.
7. Potential for Segmentation Faults: Dereferencing an invalid or null pointer can result in a segmentation
fault, causing program termination.