Pointer Full C Code Examples - PDF
Dynamic 2D Array using malloc
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 4;
int **matrix = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
matrix[i] = malloc(cols * sizeof(int));
}
// Fill matrix
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = i * cols + j + 1;
// Print matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
// Free memory
for (int i = 0; i < rows; i++)
free(matrix[i]);
free(matrix);
return 0;
}
Simple Singly Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
Pointer Full C Code Examples - PDF
int main() {
struct Node *head = malloc(sizeof(struct Node));
struct Node *second = malloc(sizeof(struct Node));
struct Node *third = malloc(sizeof(struct Node));
head->data = 10;
head->next = second;
second->data = 20;
second->next = third;
third->data = 30;
third->next = NULL;
printList(head);
// Free memory
free(third);
free(second);
free(head);
return 0;
}
Insert Node at End of Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertEnd(struct Node** head, int value) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
Pointer Full C Code Examples - PDF
void printList(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 10);
insertEnd(&head, 20);
insertEnd(&head, 30);
printList(head);
// Free memory (manually)
struct Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
return 0;
}