42. What is Pointer? Why it is important? List out Benefits of using a pointer.
- The pointer in C language is a variable which stores the address of another variable.
- This variable can be of type int, char, array, function, or any other pointer.
- Consider the following example to define a pointer which stores the address of an integer.
int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Important of Pointer
- C uses pointers to create dynamic data structures, data structures built up from
- blocks of memory allocated from the heap at run-time. Example linked list, tree, etc.
- C uses pointers to handle variable parameters passed to functions.
- Pointers in C provide an alternative way to access information stored in arrays.
- Pointer use in system level programming where memory addresses are useful. For
- example shared memory used by multiple threads.
- Pointers are used for file handling.
- This is the reason why C is versatile.
43. How to Access address of a variable and How to access a variable through its Pointer.
To access the address of a variable, you can use the “address-of” operator (&). This operator returns the memory address of a variable. Here’s an example:
#include <stdio.h>
#include<conio.h>
int main() {
int num = 42;
printf("The address of num is: %pn", &num); // %p is used to print the address in hexadecimal format
getch();
}
In this example, we have a variable num
declared with the value 42. The expression &num
is used to obtain the address of num
. By using %p
in the printf
function, we can print the address.
To access a variable through its pointer, you need to declare a pointer variable and assign the address of the variable to the pointer. Then, you can use the pointer to manipulate the variable indirectly. Here’s an example:
#include <stdio.h>
#include<conio.h>
int main() {
int num = 42;
int* ptr = # // Declaring a pointer and assigning the address of num to it
printf("The value of num is: %dn", num);
printf("The value of num through its pointer is: %dn", *ptr); // Accessing the value through the pointer
*ptr = 100; // Modifying the value of num through its pointer
printf("The new value of num is: %dn", num);
getch();
}
In this example, we declare a pointer variable ptr
of type int*
. We assign the address of num
to ptr
using the address-of operator (&num
). The value of num
can be accessed indirectly through the pointer using the dereference operator (*ptr
). Modifying the value through the pointer (*ptr = 100;
) affects the original variable num
.
When printing the value of num
through its pointer (*ptr
), it will give the same result as accessing num
directly. Modifying the value of num
through its pointer will also change the value of num
.
44. Difference between Call by Value and Call by Reference.
Call by Value and Call by Reference are two different ways of passing arguments to functions in programming languages. Let’s understand the differences between them:
Call by Value :
- In Call by Value, a copy of the actual argument is passed to the function parameter.
- Any modifications made to the parameter within the function do not affect the original argument.
- The value of the original argument remains unchanged outside the function.
- Primitive data types, such as integers, floats, and characters, are typically passed by value.
Example of Call by Value:
void increment(int num) {
num = num + 1;
printf("Inside function: %dn", num);
}
int main() {
int num = 5;
increment(num);
printf("Outside function: %dn", num);
return 0;
}
Output:
Inside function: 6
Outside function: 5
In the example above, the value of num
is passed to the increment
function by value. The function increments the value by 1, but the original num
variable in the main
function remains unchanged.
Call by Reference :
- In Call by Reference, the memory address (reference) of the actual argument is passed to the function parameter.
- Any modifications made to the parameter within the function directly affect the original argument.
- The value of the original argument can be changed outside the function.
- Pointers or reference types are typically used for call by reference.
Example of Call by Reference:
void incrementByReference(int *ptr) {
(*ptr)++;
printf("Inside function: %dn", *ptr);
}
int main() {
int num = 5;
incrementByReference(&num);
printf("Outside function: %dn", num);
return 0;
}
Output:
Inside function: 6
Outside function: 6
In the example above, the memory address of num
is passed to the incrementByReference
function using a pointer. The function increments the value by 1, and the change is reflected in the original num
variable in the main
function.
In summary, Call by Value passes a copy of the value to the function, while Call by Reference passes the memory address of the value. Call by Reference allows modifying the original value within the function, while Call by Value does not.
45. Any Program of Pointer could be asked.
Click Here. For Pointer programs ( Program 01 – 03)
46. What is Structure? Why it is important.
- Structure is a collection of logically related data items of different datatypes grouped together under single name.
- Structure is a user defined datatype.
- Structure helps to build a complex datatype which is more meaningful than an array.
- But, an array holds similar datatype record, when structure holds different datatypes records.
- Two fundamental aspects of Structure:
- Declaration of Structure Variable
- Accessing of Structure Member
Structures are important in the C language because they:
- Group related data fields together.
- Facilitate the creation of complex data structures.
- Improve code readability and maintainability.
- Enable the creation of abstract data types.
- Allow for flexible and reusable code.
- Are essential for building smart programs.
47. How Structure is different from Array?
Structures and arrays are both used for organizing and storing data, but they have some key differences:
1) Data Organization:
- Arrays store elements of the same data type in contiguous memory locations. The elements are accessed using an index.
- Structures, on the other hand, can store elements of different data types grouped together. Each element in a structure is called a member or field and can be accessed using dot notation.
2) Flexibility:
- Arrays have a fixed size that is determined at compile time. Once an array is declared, its size cannot be changed.
- Structures provide flexibility in terms of size and composition. They can grow or shrink dynamically by adding or removing members as needed.
3) Memory Allocation:
- Arrays allocate memory for a fixed number of elements. The memory allocation is done in a contiguous block.
- Structures allocate memory for each member individually, allowing them to have different sizes and types.
4) Accessing Data:
- Array elements are accessed using an index, starting from 0. Elements are accessed directly by their position in the array.
- Structure members are accessed using the dot (.) operator, providing the member name. Each member has a unique identifier within the structure.
5) Usage:
- Arrays are commonly used when dealing with a collection of homogeneous data, such as a list of numbers or characters.
- Structures are used to represent a collection of related data with different types, such as a student record with name, age, and grade.
6) Memory Efficiency:
- Arrays are typically more memory-efficient as they store data in a contiguous block without any additional overhead.
- Structures have some overhead due to storing different members with different sizes and types, which may lead to slightly higher memory usage.
48. How to declare and initialize Structure and access the Structure Variables?
To declare and initialize a structure and access its variables, you can follow these steps:
1) Structure Declaration:
- First, you need to declare a structure using the
struct
keyword followed by the structure name. - Inside the structure, you define the variables or members that represent the data you want to store.
- Here’s an example of a structure declaration:
struct Person { char name[50]; int age; float height; };
2) Structure Variable Declaration and Initialization:
- After declaring the structure, you can declare variables of that structure type.
- To initialize the structure variables, you can use the following methods:
- Inline initialization: Initialize the structure variable at the time of declaration.
- Separate initialization: Declare the structure variable first and then assign values to its members.
- Here are examples of both methods:
// Inline initialization struct Person person1 = {"John", 25, 1.75};
// Separate initialization struct Person person2; person2.age = 30; strcpy(person2.name, "Alice"); person2.height = 1.65;
3) Accessing Structure Variables:
- Structure variables can be accessed using the dot (.) operator.
- The dot operator is used to specify the structure variable, followed by the member name.
- Here’s an example of accessing structure variables:
printf("Person 1: Name = %s, Age = %d, Height = %.2fn", person1.name, person1.age, person1.height);
printf("Person 2: Name = %s, Age = %d, Height = %.2fn", person2.name, person2.age, person2.height);
By following these steps, you can declare a structure, initialize its variables, and access the structure variables and their members. Structures provide a way to organize and store related data in a single entity, making it easier to manage and access the data.
49. Explain how to pass a Structure as an argument in function?
In programming languages like C or C++, passing a structure as an argument to a function involves the following steps:
- Define the structure: Start by defining the structure that you want to pass as an argument. A structure is a user-defined data type that allows you to group together related data fields. Here’s an example of a simple structure representing a person:
struct Person {
char name[50];
int age;
};
- Declare the function: Declare the function that will receive the structure as an argument. You need to specify the structure type in the function declaration. Here’s an example of a function that takes the
Person
structure as an argument:
void printPerson(struct Person p);
- Pass the structure as an argument: When calling the function, you can pass the structure as an argument. You can create an instance of the structure, populate its fields, and pass it to the function. Here’s an example:
int main() {
struct Person john;
strcpy(john.name, "John");
john.age = 25;
printPerson(john);
return 0;
}
- Access the structure fields in the function: Inside the function, you can access the individual fields of the structure using the dot operator (
.
). Here’s an example of theprintPerson
function implementation:
void printPerson(struct Person p) {
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
}
The function receives the Person
structure as a parameter and then prints out the name and age fields.
That’s it! By following these steps, you can pass a structure as an argument to a function. The function receives the structure, and you can access its fields to perform any necessary operations.
50. Explain Nested Structure.
Nested structures, also known as structures within structures, allow you to create complex data structures by including one structure as a member of another structure. This concept allows you to organize related data in a hierarchical manner, where the outer structure contains one or more inner structures as its members.
To understand nested structures, let’s consider an example of a library system. We can define two structures: Book
and Library
, where the Library
structure contains multiple Book
structures.
struct Book {
char title[50];
char author[50];
int year;
};
struct Library {
struct Book books[100];
int numBooks;
char location[50];
};
In this example, the Book
structure represents the information about a single book, such as its title, author, and publication year. The Library
structure represents a library and includes an array of Book
structures, along with additional information like the number of books and the library’s location.
You can create instances of these structures and access their members as follows:
int main() {
struct Library myLibrary;
strcpy(myLibrary.location, "Central Library");
myLibrary.numBooks = 2;
// Adding book 1
strcpy(myLibrary.books[0].title, "The Great Gatsby");
strcpy(myLibrary.books[0].author, "F. Scott Fitzgerald");
myLibrary.books[0].year = 1925;
// Adding book 2
strcpy(myLibrary.books[1].title, "To Kill a Mockingbird");
strcpy(myLibrary.books[1].author, "Harper Lee");
myLibrary.books[1].year = 1960;
// Accessing and printing book information
for (int i = 0; i < myLibrary.numBooks; i++) {
printf("Book %d:\n", i + 1);
printf("Title: %s\n", myLibrary.books[i].title);
printf("Author: %s\n", myLibrary.books[i].author);
printf("Year: %d\n", myLibrary.books[i].year);
printf("--------------------\n");
}
return 0;
}
In this code, we create an instance of the Library
structure named myLibrary
. We set the library’s location and the number of books it contains. We then add two books by accessing the members of the nested Book
structure within the Library
structure.
The example demonstrates how you can use nested structures to create more complex data structures. By including one structure as a member of another, you can organize and manipulate related data in a hierarchical manner.
51. Difference between Structure and Union.
Structures and unions are both compound data types in C programming, but they have some fundamental differences:
- Structure:
- A structure is a composite data type that allows you to group together variables of different data types under one name.
- Each member of a structure occupies its own memory space, and the memory required is the sum of the memory required for each member.
- Structures are used when you want to represent a collection of related data items, such as a person’s name, age, and address.
- Union:
- A union is a special data type that allows you to store different data types in the same memory space.
- In a union, all members share the same memory location, and only one member can hold a value at a time.
- Unions are used when you want to save memory by sharing memory space among different variables, such as representing a variable that can be an integer, float, or character.
52. Explain Arrays of Structures and Arrays within Structures with example.
Arrays of Structures and Arrays within Structures are concepts that allow you to organize and store related data in a structured manner in programming languages like C and C++.
Arrays of Structures: It is an array in which each element is a structure. It allows you to group multiple instances of a structure type together, enabling you to store and access multiple records of related data.
Arrays within Structures: It allows you to include arrays as members of a structure. This allows you to store collections of data within each structure element.
Example:
Arrays of Structures:
struct student {
char name[50];
int age;
};
struct student class[5]; // Array of structures
Arrays within Structures:
struct employee {
char name[50];
int hours[7]; // Array within structure to store daily working hours
};
struct employee emp; // Structure with an array member
53. Write a Program (3 marks or 4 marks) (example of program that can be asked are given below)
a. Write a program to print total and percentage of five subjects of five students using structure.
b. Write a program to scan and print Employee ID and Employee Name of five employees using structure.
54. Explain any five functions of File.
Syntax | Description |
fp=fopen(file_name, mode); | This statement opens the file and assigns an identifier to the FILE type pointer fp. Example: fp = fopen(“printfile.c”,”r”); |
fclose(filepointer); | Closes a file and release the pointer. Example: fclose(fp); |
fprintf(fp, “control string”,list); | Here fp is a file pointer associated with a file. The control string contains items to be printed. The list may includes variables, constants and strings. Example: fprintf(fp, “%s %d %c”, name, age, gender); |
Syntax | Description |
fscanf(fp, “control string”,list); | Here fp is a file pointer associated with a file. The control string contains items to be printed. The list may includes variables, constants and strings. Example: fscanf(fp, “%s %d”, &item, &qty); |
int getc(FILE *fp); | getc() returns the next character from a file referred by fp; it require the FILE pointer to tell from which file. It returns EOF for end of file or error. Example: c = getc(fp); |
int putc(int c, FILE *fp); | putc() writes or appends the character c to the FILE fp. If a putc function is successful, it returns the character written, EOF if an error occurs. Example: putc(c, fp); |
55. Write a program to read data from File and display on screen.
#include <stdio.h>
void main()
{
FILE *fp; //p is a FILE type pointer
char ch; //ch is used to store single character
fp = fopen("file1.c","r"); //open file in read mode and store file pointer in p
do { //repeat step 9 and 10 until EOF is reached
ch = getc(fp); //get character pointed by p into ch
putchar(ch); //print ch value on monitor
}while(ch != EOF); //condition to check EOF is reached or not
fclose(fp); //free up the file pointer pointed by fp
}
56. Write a program to write data to the file.
#include<stdio.h>
int main() {
FILE *file;
char data[100];
// Open the file in write mode
file = fopen("example.txt", "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Failed to open the file.n");
return 1;
}
printf("Enter data to write to the file (max 100 characters): ");
fgets(data, sizeof(data), stdin);
// Write the data to the file
fprintf(file, "%s", data);
// Close the file
fclose(file);
printf("Data written to the file successfully.n");
return 0;
}
57. Write a program to copy one file to another file.
#include <stdio.h>
void main()
{
FILE *fp1, *fp2; //p and q is a FILE type pointer
char ch; //ch is used to store temporary data
fp1 = fopen("file1.c","r"); //open file “file1.c” in read mode
fp2 = fopen("file2.c","w"); //open file “file2.c” in write mode
do { //repeat step 9 and 10 until EOF is reached
ch = getc(fp1); //get character pointed by p into ch
putc(ch, fp2); //print ch value into file, pointed by pointer q
}while(ch != EOF); //condition to check EOF is reached or not
fclose(fp1); //free up the file pointer p
fclose(fp2); //free up the file pointer q
printf("File copied successfully...");
}