Sitemap
Linking

Linking

Member-only story

Advanced Techniques in C Programming — 1

13 min readOct 27, 2024

--

1. Dynamic Memory Allocation and Pointer Arithmetic

This example dynamically allocates memory for an array and uses pointer arithmetic to fill it.

c
Copy code
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamic memory allocation
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Fill array with values and print using pointer arithmetic
for (int i = 0; i < n; i++) {
*(arr + i) = i * 2; // Store value in allocated memory
printf("%d ", *(arr + i));
}
printf("\n");
// Free allocated memory
free(arr);
return 0;
}

Expected Output:

mathematica
Copy code
Enter the number of elements: 5
0 2 4 6 8

2. File Handling: Reading and Writing to a File

This program writes to a file and then reads from it.

c
Copy code
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w");
if (file == NULL) {…

--

--