0% found this document useful (0 votes)
5 views17 pages

C Programs for Pointers and Arrays

The document provides multiple examples of using pointers to arrays and arrays of pointers in C programming. It includes programs for storing and printing student marks, temperature readings, sales data, RGB image components, and handling command-line arguments. Additionally, it demonstrates dynamic memory allocation for varying data sizes and using function pointers for mathematical operations.

Uploaded by

2drhxkrk6x
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

C Programs for Pointers and Arrays

The document provides multiple examples of using pointers to arrays and arrays of pointers in C programming. It includes programs for storing and printing student marks, temperature readings, sales data, RGB image components, and handling command-line arguments. Additionally, it demonstrates dynamic memory allocation for varying data sizes and using function pointers for mathematical operations.

Uploaded by

2drhxkrk6x
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SOME EXAMPLES ON POINTERS TO AN ARRAY AND

ARRAYS OF POINTER
Examples: Pointer to an Array
// Print all marks
for (int i = 0; i < 3; i++) { // i → student
1️⃣ Write a C program to store the marks of 3 for (int j = 0; j < 4; j++) { // j → subject
students in 4 subjects and print them. printf("%d ", p[i][j]); // p[i] is the i-th
Use a pointer to an array so that pointer arithmetic row, [j] selects the subject
moves one full row (4 integers) at a time. }
puts(""); // new line after each
#include <stdio.h> student
}
int main(void) { return 0;
// 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;
 2. Write a C program to record 7 days of
temperature readings, each day having {21.5, 26.3},
{20.7, 25.2},
 two values: morning and evening temperature. {19.9, 24.8}
The program should print only the evening };
temperature for each day using a pointer to an // 'day' is a pointer to an array of 2 floats (one full day's
array. readings)
float (*day)[2] = temp;
 #include <stdio.h>
// Print evening temperature (second column) for each
 int main(void) { day
 // 7 days × 2 readings (morning, evening) for (int i = 0; i < 7; i++)
printf("Day %d evening: %.1f\n", i + 1, day[i][1]);
 float temp[7][2] = {
 {20.1, 25.4}, return 0;
}
 {21.2, 26.0},
 {19.8, 24.5},
 {22.0, 27.1},
{20.1f, 25.4f},
 3️⃣ Write a C program that stores morning and
{21.2f, 26.0f},
evening temperature readings for 7 days and
{19.8f, 24.5f},
prints only the evening temperature for each
{22.0f, 27.1f},
day.
{21.5f, 26.3f},
Use a pointer to an array so pointer arithmetic
{20.7f, 25.2f},
moves one full day (two floats) at a time.
{19.9f, 24.8f}
 #include <stdio.h> };
/*
Declare a pointer to an array of 2 floats.
 int main(void) Each step (day + 1) moves by an entire row (2 floats).
*/
 {
float (*day)[2] = temp;
 /*
// Display only the evening (second column) reading for
 7 rows (days) × 2 columns (readings):
each day
 column 0 → morning temperature for (int i = 0; i < 7; i++) {
printf("Day %d evening temperature: %.1f °C\n",
 column 1 → evening temperature
i + 1, // display day number (1–7)
 */ day[i][1]); // column 1 is the evening temperature
 float temp[7][2] = { }

return 0;
}
4. A company keeps daily sales data for a week. int main(void) {
Each day has exactly 5 product categories. // 7 days × 5 categories: hard-coded sample data
Write a C program to calculate and print the total sales of each int week[7][5] = {
category using a pointer to an array. {10, 15, 20, 25, 30},
#include <stdio.h> {12, 18, 22, 28, 31},
{11, 14, 19, 23, 27},
// Function that receives a pointer to an array of 5 integers {13, 17, 21, 24, 29},
void category_totals(int (*sales)[5], int days) { {15, 20, 25, 30, 35},
int totals[5] = {0}; // total per category {10, 10, 10, 10, 10},
{16, 18, 19, 21, 25}
for (int d = 0; d < days; d++) { // loop over each day };
(row)
for (int c = 0; c < 5; c++) { // loop over each category // Pass to the function:
(column) // 'week' decays to type 'int (*)[5]' — pointer to array
totals[c] += sales[d][c]; // add today's sales for this of 5 ints
category category_totals(week, 7);
}
} return 0;
}
// Print results
for (int c = 0; c < 5; c++)
printf("Category %d total = %d\n", c, totals[c]);
}
 5️⃣ Write a C program to represent a tiny 2×1 RGB
image (two pixels, each with Red, Green, Blue unsigned char img[2][3] = {
components). {255, 0, 0}, // first pixel: pure red
Access the pixel data using a pointer to an array so { 0, 255, 0} // second pixel: pure green
you can move one pixel (3 bytes) at a time, and print: };
 the green component of the first pixel, and
// 'pix' is a pointer to an array of 3 unsigned chars (one
 the blue component of the second pixel. entire RGB pixel)
 #include <stdio.h> unsigned char (*pix)[3] = img;

// Access specific color channels


 int main(void) { printf("First pixel green component: %u\n", pix[0][1]); //
row 0, col 1 → Green
 /*
printf("Second pixel blue component: %u\n", pix[1][2]); //
 img[row][col] → row = pixel index row 1, col 2 → Blue
 col = color channel
return 0;
 col 0 = Red, 1 = Green, 2 = Blue }
 Two pixels:
 Pixel 0 = Red (255, 0, 0)
 Pixel 1 = Green ( 0, 255, 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: %s\n", i, cmd[i]);
 return 0;
 }
 Concepts: array of char*, NULL sentinel, strings may live in read-only memory.
2️⃣ Read names of 5 students, store each name
while (s[n] != '\0') n++; // count
with its own exact length,
until null terminator
sort them alphabetically, and print the result.
return n;
Use array of pointers and manual string
}
operations only
// ---- helper to copy one string to another -
---
 #include <stdio.h> void my_strcpy(char *dest, const char
*src) {
 #include <stdlib.h>
while ((*dest++ = *src++) != '\0'); //
copy including '\0'
}
 // ---- helper to find length of a C string ----

 size_t my_strlen(const char *s) {

 size_t n = 0;
 // ---- helper to compare two strings void sort_names(char *arr[], int n) {
alphabetically ---- for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1-i; j++) {
 // returns negative if a<b, 0 if equal, positive if (my_strcmp(arr[j], arr[j+1]) > 0) {
if a>b char *tmp = arr[j];
 int my_strcmp(const char *a, const char *b) { arr[j] = arr[j+1];
arr[j+1] = tmp;
 while (*a && (*a == *b)) { // advance }
while chars equal }
 a++; }
}
 b++;
 }
 return (unsigned char)*a - (unsigned
char)*b;
 }

 // ---- simple bubble sort of array-of-pointers --


--
 int main(void) { printf("Memory allocation failed\n");
return 1;
 char *names[5]; // array of 5
char* (array of pointers) }
my_strcpy(names[i], buffer); // manual copy
}
 // 1️⃣ Read each name and allocate exact
memory
// 2️⃣ Sort the pointers (bubble sort with our compare)
 for (int i = 0; i < 5; i++) {
sort_names(names, 5);
 char buffer[100]; // temporary
stack buffer
// 3️⃣ Print and free
 printf("Enter name %d: ", i + 1); printf("\nSorted names:\n");
 scanf("%99s", buffer); // read into for (int i = 0; i < 5; i++) {
buffer
printf("%s\n", names[i]);
free(names[i]); // free each separately
 size_t len = my_strlen(buffer); // manual }
length return 0;
 names[i] = malloc(len + 1); // allocate }
just enough (+1 for '\0')
 if (!names[i]) {
 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> for (int j = 0; j < counts[i]; j++) {
 #include <stdlib.h> printf(" Mark %d: ", j + 1);
scanf("%d", &marks[i][j]); // read each mark
}
 int main(void) {
}
 int *marks[3]; // array of 3 int pointers (one per // 2️⃣ Display marks
student) printf("\n---- Marks Entered ----\n");
 int counts[3] = {2, 3, 1}; // number of marks for each for (int i = 0; i < 3; i++) {
student printf("Student %d:", i);
for (int j = 0; j < counts[i]; j++)
 // 1️⃣ Allocate and input marks
printf(" %d", marks[i][j]);
puts(""); // newline after each student
 for (int i = 0; i < 3; i++) { }
 marks[i] = malloc(counts[i] * sizeof(int));
 if (!marks[i]) { // 3️⃣ Free allocated memory
for (int i = 0; i < 3; i++) {
 printf("Memory allocation failed\n");
free(marks[i]);
 return 1; }
 }
return 0;
}
 printf("Enter %d marks for Student %d:\n", counts[i], i);
 4️⃣ Write a C program that allows the user to
choose a mathematical operation at runtime—for // 0 = addition, 1 = subtraction
example, addition or subtraction—without using if int choice;
or switch statements.
Use an array of function pointers to store different printf("Enter 0 for add or 1 for subtract: ");
operations and call the selected one. scanf("%d", &choice);

if (choice < 0 || choice > 1) {


 #include <stdio.h> printf("Invalid choice\n");
return 1;
 // Two simple operations }
 int add(int a, int b) { return a + b; }
// Call the chosen function through the pointer table
 int sub(int a, int b) { return a - b; } int result = ops[choice](x, y);
printf("Result = %d\n", result);
 // Array of pointers to functions taking (int,int)
and returning int return 0;
 int (*ops[])(int, int) = { add, sub }; }

 int main(void) {
 int x = 10, y = 3;
 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>
int main(void) {
int members = 3; // number
of library members
 // helper to find length of a string (manual)
int books_per_member[3]; // how
 size_t str_len(const char *s) { many books each member borrowed
char **borrowed[3]; // array of
 size_t n = 0;
3 pointers-to-pointer-of-char
 while (s[n] != '\0') n++; // borrowed[i] will
itself be an array of char* (titles)
 return n;
 } // 1️⃣ Read how many books each member
borrowed
for (int i = 0; i < members; i++) {
 // helper to copy string manually printf("How many books did member %d
borrow? ", i);
 void str_copy(char *dest, const char *src) {
scanf("%d", &books_per_member[i]);
 while ((*dest++ = *src++) != '\0'); getchar(); // consume newline
 }
 // allocate an array of char* for this member str_copy(borrowed[i][j], temp); // copy into heap storage
 borrowed[i] = malloc(books_per_member[i] * sizeof(char*)); }
}
 if (!borrowed[i]) { printf("Allocation failed\n"); return 1; } // 3️⃣ Display all data
printf("\n--- Borrowed Books List ---\n");
for (int i = 0; i < members; i++) {
 // 2️⃣ Read each book title printf("Member %d borrowed:", i);
 for (int j = 0; j < books_per_member[i]; j++) { for (int j = 0; j < books_per_member[i]; j++)
printf(" \"%s\"", borrowed[i][j]);
 char temp[100]; puts("");
 printf(" Enter title %d for member %d: ", j + 1, i); }
 fgets(temp, sizeof temp, stdin);
// 4️⃣ Free all allocations
 // strip trailing newline if any for (int i = 0; i < members; i++) {
for (int j = 0; j < books_per_member[i]; j++)
 int k = 0;
free(borrowed[i][j]); // free each title
 while (temp[k] && temp[k] != '\n') k++; free(borrowed[i]); // free this member's pointer array
 temp[k] = '\0'; }
return 0;
}
 size_t len = str_len(temp);
 borrowed[i][j] = malloc(len + 1); // allocate just enough
space
 if (!borrowed[i][j]) { printf("Allocation failed\n"); return 1; }
THANK YOU

You might also like