You are on page 1of 2

Arrays in C:

• Arrays are collections of elements of the same data type stored in contiguous memory
locations.

• Elements in an array are accessed using indices, starting from 0.

• Arrays have a fixed size, specified during declaration.

Example: Array Declaration and Access

code

#include <stdio.h> int main() { int nums[5] = {1, 2, 3, 4, 5}; // Declaration and initialization of an array
int i; printf("Elements of the array: "); for (i = 0; i < 5; i++) { printf("%d ", nums[i]); // Accessing array
elements using indices } printf("\n"); return 0; }

Pointers in C:

• Pointers are variables that store memory addresses.

• They are used to manipulate memory and facilitate dynamic memory allocation.

• Pointer arithmetic allows navigating through memory.

Example: Pointer Declaration and Usage

code

#include <stdio.h> int main() { int num = 10; int *ptr; // Pointer declaration ptr = &num; // Assigning
address of num to ptr printf("Value of num: %d\n", num); printf("Address of num: %p\n", &num);
printf("Value of num using pointer: %d\n", *ptr); // Dereferencing pointer return 0; }

Dynamic Memory Allocation:

• malloc(), calloc(), and realloc() functions are used to allocate memory dynamically.

• free() function is used to deallocate memory.

Example: Dynamic Memory Allocation

code

#include <stdio.h> #include <stdlib.h> int main() { int *nums; int size = 5; nums = (int *)malloc(size *
sizeof(int)); // Allocating memory if (nums == NULL) { printf("Memory allocation failed\n"); return 1; }
printf("Enter %d numbers: ", size); for (int i = 0; i < size; i++) { scanf("%d", &nums[i]); // Reading input
into dynamically allocated array } printf("Numbers entered: "); for (int i = 0; i < size; i++) { printf("%d ",
nums[i]); // Accessing elements of dynamically allocated array } printf("\n"); free(nums); //
Deallocating memory return 0; }

File Handling in C:
• fopen(), fclose(), fread(), fwrite(), fprintf(), fscanf(), etc., are used for file handling in C.

Example: File Handling

code

#include <stdio.h> int main() { FILE *fp; char str[50]; fp = fopen("example.txt", "w"); // Opening file in
write mode if (fp == NULL) { printf("Error opening file\n"); return 1; } fprintf(fp, "Hello, World!\n"); //
Writing to file fclose(fp); // Closing file fp = fopen("example.txt", "r"); // Opening file in read mode if
(fp == NULL) { printf("Error opening file\n"); return 1; } fscanf(fp, "%[^\n]", str); // Reading from file
printf("Data from file: %s\n", str); fclose(fp); // Closing file return 0; }

You might also like