SOME EXAMPLES ON POINTERS TO AN ARRAY AND
ARRAYS OF POINTER
Examples: Pointer to an Array
1️⃣ Write a C program to store the marks of 3
students in 4 subjects and print them.
Use a pointer to an array so that pointer arithmetic
moves one full row (4 integers) at a time.
#include <stdio.h>
int main(void) {
// Marks of 3 students in 4 subjects
int marks[3][4] = {
{80, 85, 90, 75},
{70, 60, 65, 72},
{88, 92, 81, 77}
};
// p is a pointer to an array of 4 ints (one complete
row of marks)
int (*p)[4] = marks;
// Print all marks
for (int i = 0; i < 3; i++) { // i → student
for (int j = 0; j < 4; j++) { // j → subject
printf("%d ", p[i][j]); // p[i] is the i-th
row, [j] selects the subject
}
puts(""); // new line after each
student
}
return 0;
}
 2. Write a C program to record 7 days of
temperature readings, each day having
 two values: morning and evening temperature.
The program should print only the evening
temperature for each day using a pointer to an
array.
 #include <stdio.h>
 int main(void) {
 // 7 days × 2 readings (morning, evening)
 float temp[7][2] = {
 {20.1, 25.4},
 {21.2, 26.0},
 {19.8, 24.5},
 {22.0, 27.1},
{21.5, 26.3},
{20.7, 25.2},
{19.9, 24.8}
};
// 'day' is a pointer to an array of 2 floats (one full day's
readings)
float (*day)[2] = temp;
// Print evening temperature (second column) for each
day
for (int i = 0; i < 7; i++)
printf("Day %d evening: %.1fn", i + 1, day[i][1]);
return 0;
}
 3️⃣ Write a C program that stores morning and
evening temperature readings for 7 days and
prints only the evening temperature for each
day.
Use a pointer to an array so pointer arithmetic
moves one full day (two floats) at a time.
 #include <stdio.h>
 int main(void)
 {
 /*
 7 rows (days) × 2 columns (readings):
 column 0 → morning temperature
 column 1 → evening temperature
 */
 float temp[7][2] = {
{20.1f, 25.4f},
{21.2f, 26.0f},
{19.8f, 24.5f},
{22.0f, 27.1f},
{21.5f, 26.3f},
{20.7f, 25.2f},
{19.9f, 24.8f}
};
/*
Declare a pointer to an array of 2 floats.
Each step (day + 1) moves by an entire row (2 floats).
*/
float (*day)[2] = temp;
// Display only the evening (second column) reading for
each day
for (int i = 0; i < 7; i++) {
printf("Day %d evening temperature: %.1f °Cn",
i + 1, // display day number (1–7)
day[i][1]); // column 1 is the evening temperature
}
return 0;
}
int main(void) {
// 7 days × 5 categories: hard-coded sample data
int week[7][5] = {
{10, 15, 20, 25, 30},
{12, 18, 22, 28, 31},
{11, 14, 19, 23, 27},
{13, 17, 21, 24, 29},
{15, 20, 25, 30, 35},
{10, 10, 10, 10, 10},
{16, 18, 19, 21, 25}
};
// Pass to the function:
// 'week' decays to type 'int (*)[5]' — pointer to array
of 5 ints
category_totals(week, 7);
return 0;
}
4. A company keeps daily sales data for a week.
Each day has exactly 5 product categories.
Write a C program to calculate and print the total sales of each
category using a pointer to an array.
#include <stdio.h>
// Function that receives a pointer to an array of 5 integers
void category_totals(int (*sales)[5], int days) {
int totals[5] = {0}; // total per category
for (int d = 0; d < days; d++) { // loop over each day
(row)
for (int c = 0; c < 5; c++) { // loop over each category
(column)
totals[c] += sales[d][c]; // add today's sales for this
category
}
}
// Print results
for (int c = 0; c < 5; c++)
printf("Category %d total = %dn", c, totals[c]);
}
 5️⃣ Write a C program to represent a tiny 2×1 RGB
image (two pixels, each with Red, Green, Blue
components).
Access the pixel data using a pointer to an array so
you can move one pixel (3 bytes) at a time, and print:
 the green component of the first pixel, and
 the blue component of the second pixel.
 #include <stdio.h>
 int main(void) {
 /*
 img[row][col] → row = pixel index
 col = color channel
 col 0 = Red, 1 = Green, 2 = Blue
 Two pixels:
 Pixel 0 = Red (255, 0, 0)
 Pixel 1 = Green ( 0, 255, 0)
 */
unsigned char img[2][3] = {
{255, 0, 0}, // first pixel: pure red
{ 0, 255, 0} // second pixel: pure green
};
// 'pix' is a pointer to an array of 3 unsigned chars (one
entire RGB pixel)
unsigned char (*pix)[3] = img;
// Access specific color channels
printf("First pixel green component: %un", pix[0][1]); //
row 0, col 1 → Green
printf("Second pixel blue component: %un", pix[1][2]); //
row 1, col 2 → Blue
return 0;
}
 Examples: Array of Pointers
 (Many independent pointers, possibly different sizes)
 1️⃣ Command-Line Arguments Style
 Problem: Store a program command as separate words.
 #include <stdio.h>
 int main(void) {
 char *cmd[] = {"gcc", "-O2", "main.c", "-o", "prog", NULL};
 for (int i = 0; cmd[i] != NULL; i++)
 printf("Argument %d: %sn", i, cmd[i]);
 return 0;
 }
 Concepts: array of char*, NULL sentinel, strings may live in read-only memory.
 #include <stdio.h>
 #include <stdlib.h>
 // ---- helper to find length of a C string ----
 size_t my_strlen(const char *s) {
 size_t n = 0;
2️⃣ Read names of 5 students, store each name
with its own exact length,
sort them alphabetically, and print the result.
Use array of pointers and manual string
operations only
while (s[n] != '0') n++; // count
until null terminator
return n;
}
// ---- helper to copy one string to another -
---
void my_strcpy(char *dest, const char
*src) {
while ((*dest++ = *src++) != '0'); //
copy including '0'
}
 // ---- helper to compare two strings
alphabetically ----
 // returns negative if a<b, 0 if equal, positive
if a>b
 int my_strcmp(const char *a, const char *b) {
 while (*a && (*a == *b)) { // advance
while chars equal
 a++;
 b++;
 }
 return (unsigned char)*a - (unsigned
char)*b;
 }
 // ---- simple bubble sort of array-of-pointers --
--
void sort_names(char *arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1-i; j++) {
if (my_strcmp(arr[j], arr[j+1]) > 0) {
char *tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
 int main(void) {
 char *names[5]; // array of 5
char* (array of pointers)
 // 1️⃣ Read each name and allocate exact
memory
 for (int i = 0; i < 5; i++) {
 char buffer[100]; // temporary
stack buffer
 printf("Enter name %d: ", i + 1);
 scanf("%99s", buffer); // read into
buffer
 size_t len = my_strlen(buffer); // manual
length
 names[i] = malloc(len + 1); // allocate
just enough (+1 for '0')
 if (!names[i]) {
printf("Memory allocation failedn");
return 1;
}
my_strcpy(names[i], buffer); // manual copy
}
// 2️⃣ Sort the pointers (bubble sort with our compare)
sort_names(names, 5);
// 3️⃣ Print and free
printf("nSorted names:n");
for (int i = 0; i < 5; i++) {
printf("%sn", names[i]);
free(names[i]); // free each separately
}
return 0;
}
 3️⃣ Create a C program that:
 Stores marks for 3 students.
 Each student can have a different number of marks (for example, different subjects).
 The number of marks for each student is known in advance and stored in an array.
 The program must:
 Dynamically allocate exactly enough memory for each student.
 Read all marks from the user.
 Display the marks for each student.
 Free the allocated memory..
 #include <stdio.h>
 #include <stdlib.h>
 int main(void) {
 int *marks[3]; // array of 3 int pointers (one per
student)
 int counts[3] = {2, 3, 1}; // number of marks for each
student
 // 1️⃣ Allocate and input marks
 for (int i = 0; i < 3; i++) {
 marks[i] = malloc(counts[i] * sizeof(int));
 if (!marks[i]) {
 printf("Memory allocation failedn");
 return 1;
 }
 printf("Enter %d marks for Student %d:n", counts[i], i);
for (int j = 0; j < counts[i]; j++) {
printf(" Mark %d: ", j + 1);
scanf("%d", &marks[i][j]); // read each mark
}
}
// 2️⃣ Display marks
printf("n---- Marks Entered ----n");
for (int i = 0; i < 3; i++) {
printf("Student %d:", i);
for (int j = 0; j < counts[i]; j++)
printf(" %d", marks[i][j]);
puts(""); // newline after each student
}
// 3️⃣ Free allocated memory
for (int i = 0; i < 3; i++) {
free(marks[i]);
}
return 0;
}
 4️⃣ Write a C program that allows the user to
choose a mathematical operation at runtime—for
example, addition or subtraction—without using if
or switch statements.
Use an array of function pointers to store different
operations and call the selected one.
 #include <stdio.h>
 // Two simple operations
 int add(int a, int b) { return a + b; }
 int sub(int a, int b) { return a - b; }
 // Array of pointers to functions taking (int,int)
and returning int
 int (*ops[])(int, int) = { add, sub };
 int main(void) {
 int x = 10, y = 3;
// 0 = addition, 1 = subtraction
int choice;
printf("Enter 0 for add or 1 for subtract: ");
scanf("%d", &choice);
if (choice < 0 || choice > 1) {
printf("Invalid choicen");
return 1;
}
// Call the chosen function through the pointer table
int result = ops[choice](x, y);
printf("Result = %dn", result);
return 0;
}
 A library wants to keep track of the book titles borrowed by different members.
 Each member can borrow a different number of books.
 We must store the titles (strings) for each member, then display them.
 No standard string functions like strlen, strcpy, or strcmp are allowed—everything is done manually.
 This is a perfect array of pointers situation because:
 Each member’s list of book titles is independent.
 Each title has a variable length.
 #include <stdio.h>
 #include <stdlib.h>
 // helper to find length of a string (manual)
 size_t str_len(const char *s) {
 size_t n = 0;
 while (s[n] != '0') n++;
 return n;
 }
 // helper to copy string manually
 void str_copy(char *dest, const char *src) {
 while ((*dest++ = *src++) != '0');
 }
int main(void) {
int members = 3; // number
of library members
int books_per_member[3]; // how
many books each member borrowed
char **borrowed[3]; // array of
3 pointers-to-pointer-of-char
// borrowed[i] will
itself be an array of char* (titles)
// 1️⃣ Read how many books each member
borrowed
for (int i = 0; i < members; i++) {
printf("How many books did member %d
borrow? ", i);
scanf("%d", &books_per_member[i]);
getchar(); // consume newline
 // allocate an array of char* for this member
 borrowed[i] = malloc(books_per_member[i] * sizeof(char*));
 if (!borrowed[i]) { printf("Allocation failedn"); return 1; }
 // 2️⃣ Read each book title
 for (int j = 0; j < books_per_member[i]; j++) {
 char temp[100];
 printf(" Enter title %d for member %d: ", j + 1, i);
 fgets(temp, sizeof temp, stdin);
 // strip trailing newline if any
 int k = 0;
 while (temp[k] && temp[k] != 'n') k++;
 temp[k] = '0';
 size_t len = str_len(temp);
 borrowed[i][j] = malloc(len + 1); // allocate just enough
space
 if (!borrowed[i][j]) { printf("Allocation failedn"); return 1; }
str_copy(borrowed[i][j], temp); // copy into heap storage
}
}
// 3️⃣ Display all data
printf("n--- Borrowed Books List ---n");
for (int i = 0; i < members; i++) {
printf("Member %d borrowed:", i);
for (int j = 0; j < books_per_member[i]; j++)
printf(" "%s"", borrowed[i][j]);
puts("");
}
// 4️⃣ Free all allocations
for (int i = 0; i < members; i++) {
for (int j = 0; j < books_per_member[i]; j++)
free(borrowed[i][j]); // free each title
free(borrowed[i]); // free this member's pointer array
}
return 0;
}
THANK YOU

C Programming examples on Arrays and Pointers.pdf

  • 1.
    SOME EXAMPLES ONPOINTERS TO AN ARRAY AND ARRAYS OF POINTER
  • 2.
    Examples: Pointer toan Array 1️⃣ Write a C program to store the marks of 3 students in 4 subjects and print them. Use a pointer to an array so that pointer arithmetic moves one full row (4 integers) at a time. #include <stdio.h> int main(void) { // Marks of 3 students in 4 subjects int marks[3][4] = { {80, 85, 90, 75}, {70, 60, 65, 72}, {88, 92, 81, 77} }; // p is a pointer to an array of 4 ints (one complete row of marks) int (*p)[4] = marks; // Print all marks for (int i = 0; i < 3; i++) { // i → student for (int j = 0; j < 4; j++) { // j → subject printf("%d ", p[i][j]); // p[i] is the i-th row, [j] selects the subject } puts(""); // new line after each student } return 0; }
  • 3.
     2. Writea C program to record 7 days of temperature readings, each day having  two values: morning and evening temperature. The program should print only the evening temperature for each day using a pointer to an array.  #include <stdio.h>  int main(void) {  // 7 days × 2 readings (morning, evening)  float temp[7][2] = {  {20.1, 25.4},  {21.2, 26.0},  {19.8, 24.5},  {22.0, 27.1}, {21.5, 26.3}, {20.7, 25.2}, {19.9, 24.8} }; // 'day' is a pointer to an array of 2 floats (one full day's readings) float (*day)[2] = temp; // Print evening temperature (second column) for each day for (int i = 0; i < 7; i++) printf("Day %d evening: %.1fn", i + 1, day[i][1]); return 0; }
  • 4.
     3️⃣ Writea C program that stores morning and evening temperature readings for 7 days and prints only the evening temperature for each day. Use a pointer to an array so pointer arithmetic moves one full day (two floats) at a time.  #include <stdio.h>  int main(void)  {  /*  7 rows (days) × 2 columns (readings):  column 0 → morning temperature  column 1 → evening temperature  */  float temp[7][2] = { {20.1f, 25.4f}, {21.2f, 26.0f}, {19.8f, 24.5f}, {22.0f, 27.1f}, {21.5f, 26.3f}, {20.7f, 25.2f}, {19.9f, 24.8f} }; /* Declare a pointer to an array of 2 floats. Each step (day + 1) moves by an entire row (2 floats). */ float (*day)[2] = temp; // Display only the evening (second column) reading for each day for (int i = 0; i < 7; i++) { printf("Day %d evening temperature: %.1f °Cn", i + 1, // display day number (1–7) day[i][1]); // column 1 is the evening temperature } return 0; }
  • 5.
    int main(void) { //7 days × 5 categories: hard-coded sample data int week[7][5] = { {10, 15, 20, 25, 30}, {12, 18, 22, 28, 31}, {11, 14, 19, 23, 27}, {13, 17, 21, 24, 29}, {15, 20, 25, 30, 35}, {10, 10, 10, 10, 10}, {16, 18, 19, 21, 25} }; // Pass to the function: // 'week' decays to type 'int (*)[5]' — pointer to array of 5 ints category_totals(week, 7); return 0; } 4. A company keeps daily sales data for a week. Each day has exactly 5 product categories. Write a C program to calculate and print the total sales of each category using a pointer to an array. #include <stdio.h> // Function that receives a pointer to an array of 5 integers void category_totals(int (*sales)[5], int days) { int totals[5] = {0}; // total per category for (int d = 0; d < days; d++) { // loop over each day (row) for (int c = 0; c < 5; c++) { // loop over each category (column) totals[c] += sales[d][c]; // add today's sales for this category } } // Print results for (int c = 0; c < 5; c++) printf("Category %d total = %dn", c, totals[c]); }
  • 6.
     5️⃣ Writea C program to represent a tiny 2×1 RGB image (two pixels, each with Red, Green, Blue components). Access the pixel data using a pointer to an array so you can move one pixel (3 bytes) at a time, and print:  the green component of the first pixel, and  the blue component of the second pixel.  #include <stdio.h>  int main(void) {  /*  img[row][col] → row = pixel index  col = color channel  col 0 = Red, 1 = Green, 2 = Blue  Two pixels:  Pixel 0 = Red (255, 0, 0)  Pixel 1 = Green ( 0, 255, 0)  */ unsigned char img[2][3] = { {255, 0, 0}, // first pixel: pure red { 0, 255, 0} // second pixel: pure green }; // 'pix' is a pointer to an array of 3 unsigned chars (one entire RGB pixel) unsigned char (*pix)[3] = img; // Access specific color channels printf("First pixel green component: %un", pix[0][1]); // row 0, col 1 → Green printf("Second pixel blue component: %un", pix[1][2]); // row 1, col 2 → Blue return 0; }
  • 7.
     Examples: Arrayof Pointers  (Many independent pointers, possibly different sizes)  1️⃣ Command-Line Arguments Style  Problem: Store a program command as separate words.  #include <stdio.h>  int main(void) {  char *cmd[] = {"gcc", "-O2", "main.c", "-o", "prog", NULL};  for (int i = 0; cmd[i] != NULL; i++)  printf("Argument %d: %sn", i, cmd[i]);  return 0;  }  Concepts: array of char*, NULL sentinel, strings may live in read-only memory.
  • 8.
     #include <stdio.h> #include <stdlib.h>  // ---- helper to find length of a C string ----  size_t my_strlen(const char *s) {  size_t n = 0; 2️⃣ Read names of 5 students, store each name with its own exact length, sort them alphabetically, and print the result. Use array of pointers and manual string operations only while (s[n] != '0') n++; // count until null terminator return n; } // ---- helper to copy one string to another - --- void my_strcpy(char *dest, const char *src) { while ((*dest++ = *src++) != '0'); // copy including '0' }
  • 9.
     // ----helper to compare two strings alphabetically ----  // returns negative if a<b, 0 if equal, positive if a>b  int my_strcmp(const char *a, const char *b) {  while (*a && (*a == *b)) { // advance while chars equal  a++;  b++;  }  return (unsigned char)*a - (unsigned char)*b;  }  // ---- simple bubble sort of array-of-pointers -- -- void sort_names(char *arr[], int n) { for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-1-i; j++) { if (my_strcmp(arr[j], arr[j+1]) > 0) { char *tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } }
  • 10.
     int main(void){  char *names[5]; // array of 5 char* (array of pointers)  // 1️⃣ Read each name and allocate exact memory  for (int i = 0; i < 5; i++) {  char buffer[100]; // temporary stack buffer  printf("Enter name %d: ", i + 1);  scanf("%99s", buffer); // read into buffer  size_t len = my_strlen(buffer); // manual length  names[i] = malloc(len + 1); // allocate just enough (+1 for '0')  if (!names[i]) { printf("Memory allocation failedn"); return 1; } my_strcpy(names[i], buffer); // manual copy } // 2️⃣ Sort the pointers (bubble sort with our compare) sort_names(names, 5); // 3️⃣ Print and free printf("nSorted names:n"); for (int i = 0; i < 5; i++) { printf("%sn", names[i]); free(names[i]); // free each separately } return 0; }
  • 11.
     3️⃣ Createa C program that:  Stores marks for 3 students.  Each student can have a different number of marks (for example, different subjects).  The number of marks for each student is known in advance and stored in an array.  The program must:  Dynamically allocate exactly enough memory for each student.  Read all marks from the user.  Display the marks for each student.  Free the allocated memory..
  • 12.
     #include <stdio.h> #include <stdlib.h>  int main(void) {  int *marks[3]; // array of 3 int pointers (one per student)  int counts[3] = {2, 3, 1}; // number of marks for each student  // 1️⃣ Allocate and input marks  for (int i = 0; i < 3; i++) {  marks[i] = malloc(counts[i] * sizeof(int));  if (!marks[i]) {  printf("Memory allocation failedn");  return 1;  }  printf("Enter %d marks for Student %d:n", counts[i], i); for (int j = 0; j < counts[i]; j++) { printf(" Mark %d: ", j + 1); scanf("%d", &marks[i][j]); // read each mark } } // 2️⃣ Display marks printf("n---- Marks Entered ----n"); for (int i = 0; i < 3; i++) { printf("Student %d:", i); for (int j = 0; j < counts[i]; j++) printf(" %d", marks[i][j]); puts(""); // newline after each student } // 3️⃣ Free allocated memory for (int i = 0; i < 3; i++) { free(marks[i]); } return 0; }
  • 13.
     4️⃣ Writea C program that allows the user to choose a mathematical operation at runtime—for example, addition or subtraction—without using if or switch statements. Use an array of function pointers to store different operations and call the selected one.  #include <stdio.h>  // Two simple operations  int add(int a, int b) { return a + b; }  int sub(int a, int b) { return a - b; }  // Array of pointers to functions taking (int,int) and returning int  int (*ops[])(int, int) = { add, sub };  int main(void) {  int x = 10, y = 3; // 0 = addition, 1 = subtraction int choice; printf("Enter 0 for add or 1 for subtract: "); scanf("%d", &choice); if (choice < 0 || choice > 1) { printf("Invalid choicen"); return 1; } // Call the chosen function through the pointer table int result = ops[choice](x, y); printf("Result = %dn", result); return 0; }
  • 14.
     A librarywants to keep track of the book titles borrowed by different members.  Each member can borrow a different number of books.  We must store the titles (strings) for each member, then display them.  No standard string functions like strlen, strcpy, or strcmp are allowed—everything is done manually.  This is a perfect array of pointers situation because:  Each member’s list of book titles is independent.  Each title has a variable length.
  • 15.
     #include <stdio.h> #include <stdlib.h>  // helper to find length of a string (manual)  size_t str_len(const char *s) {  size_t n = 0;  while (s[n] != '0') n++;  return n;  }  // helper to copy string manually  void str_copy(char *dest, const char *src) {  while ((*dest++ = *src++) != '0');  } int main(void) { int members = 3; // number of library members int books_per_member[3]; // how many books each member borrowed char **borrowed[3]; // array of 3 pointers-to-pointer-of-char // borrowed[i] will itself be an array of char* (titles) // 1️⃣ Read how many books each member borrowed for (int i = 0; i < members; i++) { printf("How many books did member %d borrow? ", i); scanf("%d", &books_per_member[i]); getchar(); // consume newline
  • 16.
     // allocatean array of char* for this member  borrowed[i] = malloc(books_per_member[i] * sizeof(char*));  if (!borrowed[i]) { printf("Allocation failedn"); return 1; }  // 2️⃣ Read each book title  for (int j = 0; j < books_per_member[i]; j++) {  char temp[100];  printf(" Enter title %d for member %d: ", j + 1, i);  fgets(temp, sizeof temp, stdin);  // strip trailing newline if any  int k = 0;  while (temp[k] && temp[k] != 'n') k++;  temp[k] = '0';  size_t len = str_len(temp);  borrowed[i][j] = malloc(len + 1); // allocate just enough space  if (!borrowed[i][j]) { printf("Allocation failedn"); return 1; } str_copy(borrowed[i][j], temp); // copy into heap storage } } // 3️⃣ Display all data printf("n--- Borrowed Books List ---n"); for (int i = 0; i < members; i++) { printf("Member %d borrowed:", i); for (int j = 0; j < books_per_member[i]; j++) printf(" "%s"", borrowed[i][j]); puts(""); } // 4️⃣ Free all allocations for (int i = 0; i < members; i++) { for (int j = 0; j < books_per_member[i]; j++) free(borrowed[i][j]); // free each title free(borrowed[i]); // free this member's pointer array } return 0; }
  • 17.