UNIT-5
UNIT-5
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(4 * sizeof(int)); // Allocate memory for 4 integers
ptr[0] = 10; // Assign value
printf("%d\n", ptr[0]); // Output: 10
---
2. Significance of malloc()
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(5 * sizeof(int)); // Allocate memory for 5 integers
ptr[0] = 10; // Assign value
printf("%d\n", ptr[0]); // Output: 10
---
3. Significance of realloc()
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(3 * sizeof(int)); // Allocate memory for 3 integers
---
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(5 * sizeof(int)); // Allocate memory for 5 integers
arr[0] = 2, arr[1] = 4, arr[2] = 1, arr[3] = 8, arr[4] = 6;
---
Example:
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person p = {"John", 25}; // Initialize structure
---
Example:
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person p;
printf("Name: ");
fgets(p.name, sizeof(p.name), stdin); // Accept name
printf("Age: ");
scanf("%d", &p.age); // Accept age
---
Example:
#include <stdio.h>
struct Student {
char name[50];
int rollNo;
};
int main() {
struct Student s[5];
return 0;
}
---
8. Differences Between Structure and Union
Structure: Each member has its own memory location. All members
can hold values simultaneously.
Union: All members share the same memory location. Only one
member can hold a value at any given time.
---
---
---
You can open a file in write mode and write text into it using fprintf().
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("test.txt", "w"); // Open file in write mode
fprintf(file, "Hello, World!\n"); // Write text to file
fclose(file); // Close the file
return 0;
}