Course Code: BBC103
Course: AKTU BCA 1st Year, Semester I
Unit: Arrays, Pointers and Strings
Unit III Overview
Learn how C stores groups of values, accesses objects using addresses and represents text as null-terminated character sequences. Study array operations, pointer expressions and string processing through programs and worked examples.
Topics Covered
| Syllabus area | Pages |
|---|---|
| Array representation and manipulation | 2-7 |
| 2D and multidimensional arrays | 7-11 |
| Pointers and operators | 11-14 |
| Passing pointers and arrays | 14-15 |
| Pointer arrays and function pointers | 16-18 |
| Strings and string functions | 18-23 |
| Exam questions with answers | 24-26 |
| Quick revision and key formulas | 27 |
Learning Outcomes
-
1. Declare and manipulate arrays.
-
2. Calculate addresses and offsets.
-
3. Understand pointer operators and arithmetic.
-
4. Pass arrays and pointers to functions.
-
5. Work with pointer arrays and function pointers.
-
6. Process strings and standard library functions.
Included in These Notes
24 study sections; 29 labelled diagrams; 10 colourful context images; explained C programs; worked cases; comparison tables, 24 short answers, 6 structured long answers and quick revision.
Study Approach
Understand. Identify dimensions, types, addresses and valid indices.
Compare. Distinguish arrays, pointers and strings.
Apply. Trace values and test each C example.
Core idea: Arrays group values; pointers refer to objects; strings store characters followed by a null terminator.
1. Array notation and representation
What is an array?
An array is a collection of same-type elements stored consecutively in memory. One name identifies the collection; an index selects an element. C uses zero-based indexing.

Instead of declaring five variables, declare one array of five integers. Each element occupies the same number of bytes.
int marks[5];
float temp[7];
char grade[4];
The array size gives the number of elements, not the last index. A valid index ranges from 0 to size minus 1.
Syntax
data_type array_name[size];
Why contiguous storage matters
The compiler can compute an element location directly using the base address, index and element width. This is why random access by index takes constant time when the index is valid.
Example: For a four-byte integer array starting at byte address 1000, the first element starts at 1000, the second at 1004 and the third at 1008.
Remember: An array is homogeneous; each element has the same declared type and width.

Memory representation
For an array A at base address B with element width w, the address of A[i] is B + i × w. Suppose an int occupies 4 bytes and A begins at address 1000.
| Index | Address | Value |
|---|---|---|
| 0 | 1000 | 72 |
| 1 | 1004 | 84 |
| 2 | 1008 | 65 |
| 3 | 1012 | 91 |
| 4 | 1016 | 78 |
Address of A[3] = 1000 + 3 × 4 = 1012. The actual size of int depends on the implementation; use sizeof(int).
Applications
Store marks, prices, temperatures and sequences. Arrays simplify iteration and uniform processing. Exam tip: Access out of bounds is undefined behavior.
Exam Check
If int a[7] begins at 1200 and each int is 4 bytes, calculate a[5]. Answer: 1200 + 5 × 4 = 1220. The final valid index is 6.
2. Declaring and initializing arrays
Initializer lists
An initializer supplies values at declaration. When fewer values are supplied than the stated length, remaining elements are zero-initialized.
int a[5]={10,20,30,40,50};
int b[4]={7,8};
int c[]={2,4,6};
int d[5]={0};

Omitting the length with an initializer lets the compiler infer it. d contains five zeros.
Local automatic arrays without initializers have indeterminate elements. Initialize or assign values before reading.
Array access
a[1] refers to the second element, not the first.

Access and assignment
int a[3]={5,10,15};
a[1]=25;
printf(“%d”,a[1]);
Output: 25. An indexed expression can be used on either side of an assignment.
Whole arrays cannot be assigned with = after declaration. Copy their elements using a loop.
int b[3];
for(int i=0;i<3;i++)
b[i]=a[i];
| Declaration | Meaning |
|---|---|
| int a[4] | Four int objects |
| int a[]={1,2} | Two initialized ints |
| int a[4]={0} | All four zero |
Memory trick: braces initialize; brackets index.
Array names normally convert to pointers in expressions, but not in sizeof or unary &.
Exam Check
What values does int k[6]={9,4} contain? Answer: 9, 4, 0, 0, 0, 0. Remaining entries are zero-initialized.
Design a marks-frequency array
A frequency array counts how many times each permitted value occurs. For marks categorized into grades 0 through 4, an array of five counters is sufficient. Initializing every counter to zero is essential because each increment reads the old value before writing the new one.
int grades[]={2,4,2,1,4,2,0};
int freq[5]={0};
for(int i=0;i<7;i++){
int g=grades[i];
if(g>=0 && g<5) freq[g]++;
}
| Grade | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Frequency | 1 | 1 | 3 | 0 | 2 |
The grade itself selects a counter. There is no need to maintain five separate variables or write a separate comparison for every valid grade. Reject values outside the permitted range.

Output interpretation: Grade 2 is most frequent. Sum of all five frequencies is 7, equal to the number of valid input values.
Exercise: sparse ranges
If accepted scores range from 20 to 25, declare six counters and use score-20 as the index after checking the range. A score of 23 maps to index 3. This offset technique is useful whenever data values begin at a nonzero lower bound.
3. Array traversal and input
Visiting each element
Traversal systematically processes every item, usually from index 0 through n−1. Operations include reading, displaying, counting and updating.

for(int i=0;i<n;i++)
printf(“%d “,a[i]);
The loop condition i < n prevents an invalid final access. The time required for a full traversal is O(n).
Input
scanf requires an address for an integer conversion. Write &a[i], and check that conversion succeeds.
Program: read and display
#include <stdio.h>
int main(void){
int a[5];
for(int i=0;i<5;i++){
if(scanf(“%d”,&a[i])!=1)
return 1;
}
for(int i=0;i<5;i++)
printf(“%d “,a[i]);
return 0;
}
Input: 8 4 11 2 9
Output: 8 4 11 2 9
| Step | Index | Printed |
|---|---|---|
| 1 | 0 | 8 |
| 2 | 1 | 4 |
| 3 | 2 | 11 |
| 4 | 3 | 2 |
| 5 | 4 | 9 |
The input loop writes each position once, and the output loop reads those positions.
Exam Check
How many times does for(i=0;i<7;i++) execute? Answer: Seven times, with indices 0 to 6.
4. Manipulating array elements
Sum and average
Initialize an accumulator to zero. Add every element. Divide by the count using floating-point division to preserve the fraction.
int a[]={4,7,2,9};
int sum=0;
for(int i=0;i<4;i++)
sum+=a[i];
double avg=sum/4.0;
| i | a[i] | sum |
|---|---|---|
| 0 | 4 | 4 |
| 1 | 7 | 11 |
| 2 | 2 | 13 |
| 3 | 9 | 22 |
Sum = 22; average = 5.5.
For large values a wider accumulator may be necessary; ensure its range is sufficient.

Minimum and maximum
Start both from the first element of a nonempty array.
int min=a[0],max=a[0];
for(int i=1;i<4;i++){
if(a[i]<min)min=a[i];
if(a[i]>max)max=a[i];
}
For the example, minimum = 2 and maximum = 9. Starting from zero would fail on all-positive minima or all-negative maxima.
Update each element
for(int i=0;i<4;i++)
a[i]*=2;

This changes the original array in place; no additional array is required.
Exam Check
For −5, −9, −2, what is the maximum? Answer: −2. Initialize from the first element, not zero.
Find the second-largest distinct element
Finding the highest value is simple, but the second distinct value requires special care when duplicates occur. Do not set the second value to zero: all elements may be negative.
#include <stdio.h>
int main(void){
int a[]={9,3,9,6,2};
int max=a[0],second=0,found=0;
for(int i=1;i<5;i++){
if(a[i]>max){
second=max;found=1;max=a[i];
}else if(a[i]<max &&
(!found||a[i]>second)){
second=a[i];found=1;
}
}
if(found)printf(“%d”,second);
else puts(“No distinct second”);
return 0;
}
Output: 6.
| Read value | Largest | Second |
|---|---|---|
| 9 | 9 | Not found |
| 3 | 9 | 3 |
| 9 | 9 | 3 |
| 6 | 9 | 6 |
| 2 | 9 | 6 |
The found flag separates the mathematical result from the initial value used in storage. Repeated copies of 9 do not qualify as a different second-largest value.
Count values above the mean
For {4, 8, 12, 16}, the sum is 40 and mean is 10. A second traversal counts the values greater than 10: 12 and 16, giving a count of 2. Computing the mean first avoids comparing against an incomplete running average.
5. Insertion, deletion and reversal
Insertion
The physical capacity of an array is fixed, but its logical length can change within that capacity. Verify n < capacity and 0 ≤ pos ≤ n.
int a[6]={10,20,30,40};
int n=4,pos=2;
for(int i=n;i>pos;i–)
a[i]=a[i-1];
a[pos]=25;
n++;

Shift occupied elements from right to left. Otherwise an element may be overwritten before its value is copied.
Insertion takes O(n) time in the worst case.
Deletion
Check that 0 ≤ pos < n, then shift the following items left. Capacity does not change.
for(int i=pos;i<n-1;i++)
a[i]=a[i+1];
n–;
Reversal
Exchange the first and last elements and move inward.
for(int i=0,j=n-1;i<j;i++,j–){
int t=a[i];
a[i]=a[j];
a[j]=t;
}

In-place reversal is O(n) time with O(1) additional storage.
Exam tip: use the logical length rather than capacity when processing active elements.
Exam Check
Delete index 1 from {4,8,12,16}. Answer: Shift 12 and 16 left; logical array becomes {4,12,16}.
Rotate an array by one position
A right rotation moves the last element to the beginning and shifts all other elements one position right. Unlike reversal, the relative cyclic order is maintained.
#include <stdio.h>
int main(void){
int a[]={10,20,30,40,50};
int last=a[4];
for(int i=4;i>0;i–)
a[i]=a[i-1];
a[0]=last;
for(int i=0;i<5;i++)
printf(“%d “,a[i]);
return 0;
}
Output: 50 10 20 30 40

Save the last value before any shifts. Rightward shifts must run from the last slot toward the first slot to avoid overwriting an unread value.
| Move | Array result |
|---|---|
| Original | 10 20 30 40 50 |
| Save 50 | 50 in temporary |
| Shift right | 10 10 20 30 40 |
| Write a[0] | 50 10 20 30 40 |
Combine two arrays
Suppose a has three elements and b has two. Copy a’s three elements into destination c starting at 0, then copy b starting at index 3. The destination must hold five elements. The resulting logical length is the sum of both input lengths. This is concatenation of arrays, not necessarily ordered merging.
int a[]={1,3,5},b[]={2,4};
int c[5];
for(int i=0;i<3;i++)c[i]=a[i];
for(int i=0;i<2;i++)c[3+i]=b[i];
The result is {1,3,5,2,4}. Each destination index is written exactly once.
6. Arrays of unknown or varying size
Inferred length
The compiler infers a length from an initializer when a dimension is omitted.
int a[]={5,10,15,20};
size_t n=sizeof a/sizeof a[0];
sizeof a measures total bytes of the array object. Dividing by element size gives the number of elements. This method does not work on a pointer parameter.
An incomplete array declaration with extern may refer to a definition elsewhere.
extern int values[];
The declaration does not allocate storage by itself. A compatible definition must exist.
Fixed arrays
The number of elements stays fixed during the lifetime of an array.
Variable-length arrays
On implementations supporting VLAs, a block-scope array can have a positive runtime length.
int n;
if(scanf(“%d”,&n)!=1 ||
n<=0 || n>1000) return 1;
int a[n];
A VLA does not resize automatically. Its lifetime ends when control leaves its scope. Some implementations do not support VLAs, so a fixed maximum is often simpler for portability.
| Kind | Length determined |
|---|---|
| Fixed | Constant bound |
| Inferred | Initializer |
| VLA | At runtime |
Dynamic allocation is another way to obtain runtime-sized storage; its library functions appear in Unit V.
Exam Check
Can a VLA with length 5 be resized by assigning n=9? Answer: No. Changing n does not change an existing array.
Runtime size with checked input
When the number of values is unknown until execution, use a bounded fixed array or a supported variable-length array. In both cases, validate the requested size before accessing elements.
#include <stdio.h>
int main(void){
int n,a[50];
long sum=0;
if(scanf(“%d”,&n)!=1 ||
n<1 || n>50)return 1;
for(int i=0;i<n;i++){
if(scanf(“%d”,&a[i])!=1)
return 1;
sum+=a[i];
}
printf(“%.2f”,(double)sum/n);
return 0;
}
Sample input: 4 12 15 18 19. Output: 16.00.
Notice that capacity is 50 but logical length is 4. The program reads only the initialized elements, and the positive length prevents division by zero. Choose a wider accumulator where necessary.
| Declaration | Valid count |
|---|---|
| int a[50] | 1 through 50 used |
| int a[n] | Positive checked n |
| int a[]={1,2} | Exactly 2 |
Sizeof worked example
Assume int occupies 4 bytes and a contains 15 integers. sizeof a is 60, sizeof a[0] is 4, and the ratio is 15. This calculation works on the actual array object. If a is replaced by a pointer variable then sizeof a is only the pointer object’s size, so the ratio no longer determines the element count.
7. Two-dimensional arrays
Rows and columns
A 2D array is an array whose elements are arrays. It represents matrices, marks tables and grids.
int m[2][3]={{1,2,3},{4,5,6}};


The first index selects a row; the second selects a column. m[1][2] equals 6. A matrix with R rows and C columns stores R × C elements.

Row-major layout
C places each row contiguously, then the next row. For array A[R][C], with element width w, address of A[i][j] = B+(i×C+j)×w.
For B=2000, C=3, w=4, A[1][2] is at 2020.
| Element | Byte offset |
|---|---|
| A[0][0] | 0 |
| A[0][1] | 4 |
| A[0][2] | 8 |
| A[1][0] | 12 |
| A[1][1] | 16 |
| A[1][2] | 20 |
Valid row indices range from 0 to R−1; valid column indices range from 0 to C−1.
Each dimension must be checked independently.
Exam Check
For an int matrix [3][4], what is the offset of [2][1]? Answer: 9 elements, or 36 bytes if int is four bytes.
Derive a two-dimensional address formula
In row-major layout, every complete row contains C elements. To reach A[i][j], skip i complete rows (i×C elements), then skip j elements in the selected row. Multiplying by the element size w gives the byte offset.
| Row | First logical element |
|---|---|
| 0 | A[0][0] |
| 1 | A[1][0] at offset C×w |
| 2 | A[2][0] at offset 2×C×w |
Worked numerical: A[5][4] starts at 1200, with two-byte elements. Find A[3][2]. Count skipped elements: 3×4+2=14. Byte offset = 14×2=28. Address = 1228.

Recover row and column from an offset
For A[4][5] with four-byte elements, suppose an element lies 52 bytes from the base. Divide by 4 to obtain element offset 13. Integer division 13/5 gives row 2, and 13%5 gives column 3. Therefore the location is A[2][3]. This procedure assumes the supplied address is aligned to an element within the array.
Practice: A[3][6] has base 3000, w=4. A[2][4] lies at 3000+(12+4)×4=3064. The largest valid logical index is 17, so A[2][5] is at 3068.
8. Matrix traversal and addition
Nested loops
Use the outer loop for rows and an inner loop for columns.
int a[2][3]={{1,2,3},{4,5,6}};
for(int i=0;i<2;i++){
for(int j=0;j<3;j++)
printf(“%d “,a[i][j]);
puts(“”);
}
Output: 1 2 3 4 5 6
| Order | Outer loop | Inner loop |
|---|---|---|
| Row-wise | i | j |
| Column-wise | j | i |
Both forms visit all R×C elements.
Addition
Matrices must have identical dimensions. Add corresponding elements to form the result.
Program: matrix addition
#include <stdio.h>
int main(void){
int a[2][2]={{1,2},{3,4}};
int b[2][2]={{5,6},{7,8}};
int c[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j]=a[i][j]+b[i][j];
printf(“%d “,c[i][j]);
}
puts(“”);
}
return 0;
}
Output: 6 8 10 12

Time complexity O(R×C).
Exam Check
What dimensions must B have when adding A[2][3] and B? Answer: B must be [2][3]; the result also has 2 rows and 3 columns.
Row totals and column totals
Matrix processing often needs aggregate values in two directions. A row-total loop resets the accumulator at the start of every row. A column-total loop resets it at the start of each column.
#include <stdio.h>
int main(void){
int m[2][3]={{3,2,4},{5,1,6}};
for(int i=0;i<2;i++){
int sum=0;
for(int j=0;j<3;j++)
sum+=m[i][j];
printf(“%d “,sum);
}
puts(“”);
for(int j=0;j<3;j++){
int sum=0;
for(int i=0;i<2;i++)
sum+=m[i][j];
printf(“%d “,sum);
}
return 0;
}
Output: row totals 9 12; column totals 8 3 10.
| Row | C0 | C1 | C2 | Total |
|---|---|---|---|---|
| 0 | 3 | 2 | 4 | 9 |
| 1 | 5 | 1 | 6 | 12 |
| Total | 8 | 3 | 10 | 21 |
The sum of the row totals equals the sum of the column totals. In this case 9+12=8+3+10=21. This is a useful check for arithmetic and loop mistakes.
Main diagonal and other diagonal
For a square matrix of order n, main diagonal elements satisfy i==j. The opposite diagonal satisfies i+j==n-1. For an odd order matrix the center appears on both diagonals; count it once when computing the union of both diagonals.
9. Matrix transpose and multiplication
Transpose
Transpose exchanges rows and columns. If A is R×C, the transpose T is C×R.
int a[2][3]={{1,2,3},{4,5,6}};
int t[3][2];
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
t[j][i]=a[i][j];
| Row of A | Column of T |
|---|---|
| 1 2 3 | 1 2 3 |
| 4 5 6 | 4 5 6 |
The transpose has rows {1,4}, {2,5}, {3,6}.
A square matrix can be transposed in place by swapping elements above and below the diagonal. The operation takes O(R×C).
Multiplication
A matrix of size R×K can multiply one of size K×C. The result has R rows and C columns. Each cell is the dot product of a row and column.
int a[2][2]={{1,2},{3,4}};
int b[2][2]={{5,6},{7,8}};
int c[2][2]={0};
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
c[i][j]+=a[i][k]*b[k][j];
c[0][0] = 1×5 + 2×7 = 19.

Second row: 43, 50. General time complexity O(R×C×K).
Exam Check
Can a 2×3 matrix multiply a 3×4 matrix? Answer: Yes; the result is 2×4. Each cell sums three products.
Full matrix multiplication program
Multiply a 2×3 matrix by a 3×2 matrix. Every output element is the dot product of one row and one column. The output shape is 2×2.
#include <stdio.h>
int main(void){
int a[2][3]={{1,2,3},{4,5,6}};
int b[3][2]={{1,0},{0,1},{1,1}};
int c[2][2]={0};
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<3;k++)
c[i][j]+=a[i][k]*b[k][j];
printf(“%d “,c[i][j]);
}
puts(“”);
}
return 0;
}
Output: first row 4 5, second row 10 11.
| Cell | Products | Result |
|---|---|---|
| c[0][0] | 1×1+2×0+3×1 | 4 |
| c[0][1] | 1×0+2×1+3×1 | 5 |
| c[1][0] | 4×1+5×0+6×1 | 10 |
| c[1][1] | 4×0+5×1+6×1 | 11 |
The innermost loop has three iterations because the two input matrices share an inner dimension of 3. The result must be initialized to zero or each cell needs a separate zero-initialized accumulator.
Matrix compatibility test
If A has R rows and K columns, B must have K rows. When B has C columns, the output dimensions are R×C. A 2×3 matrix cannot multiply a 2×3 matrix in that order, because the first matrix’s column count differs from the second matrix’s row count.
10. Multidimensional arrays
Three-dimensional arrays
A 3D array represents layers of rows and columns.
int a[2][2][3]={
{{1,2,3},{4,5,6}},
{{7,8,9},{10,11,12}}
};

a[1][0][2] = 9. The dimensions represent two layers, each containing two rows of three elements.
The last subscript changes fastest in row-major memory. A[I][J][K] contains I×J×K elements.

Address and traversal
For A[X][Y][Z], offset of A[i][j][k] = ((i×Y+j)×Z+k)×sizeof(int).
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<3;k++)
printf(“%d “,a[i][j][k]);
Base 4000 with four-byte integers: A[1][0][2] = 4032 because it is the eighth zero-based element.
| Dimensions | Application |
|---|---|
| 1D | Student marks |
| 2D | Class marks table |
| 3D | Marks in multiple terms |
Use nested loops corresponding to the array dimensions.
Exam Check
How many elements in int x[3][2][4]? Answer: 3 × 2 × 4 = 24 integers.
Three-dimensional indexing practice
A college maintains attendance values for two sections, three students per section and four days. Declare int attendance[2][3][4]. This creates 24 integers; section, student and day are independent indices.
| Dimension | Size | Valid indices |
|---|---|---|
| Section | 2 | 0,1 |
| Student | 3 | 0,1,2 |
| Day | 4 | 0,1,2,3 |
The position [1][2][3] has element offset ((1×3+2)×4+3)=23. If each int occupies four bytes and base address is 8000, the address is 8092. It is the last valid element.

Aggregate one layer
int x[2][2][2]={
{{1,2},{3,4}},
{{5,6},{7,8}}
};
int totals[2]={0};
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
totals[i]+=x[i][j][k];
The first layer total is 10 and the second is 26. A separate array stores one total per layer. By choosing which index is held fixed, you can compute totals for different dimensions.
Memory trick: Starting from the outermost index, multiply by the next dimension and add the next index, repeating until all indices are included. Multiply the final element offset by the element width.
11. Pointers: meaning and operators
Definition
A pointer is a typed value that can represent the address of an object or function. A valid object pointer provides indirect access to its target.
int x=42;
int *p=&x;
printf(“%d”,*p);

& obtains an address. Unary * dereferences a valid pointer. int *p declares a pointer to int. Addresses vary by implementation. To print an object address, use:
printf(“%p”,(void *)p);
A pointer variable is itself an object occupying memory.

Characteristics and uses
Pointers allow indirect updates, passing addresses to functions, array traversal and representing data structures.
| Expression | Meaning |
|---|---|
| x | Value of x |
| &x | Address of x |
| p | Stored pointer |
| *p | Referenced int |
| &p | Address of pointer |
*p=99;
printf(“%d”,x);
Output: 99. *p identifies the object x. Assigning through that expression changes the original variable.
Remember: a pointer declaration does not create its pointee. Initialize the pointer with a valid address before dereferencing.
Exam Check
What is the difference between p and *p? Answer: p is a pointer value; *p designates its referenced object.
12. Pointer declaration and assignment
Pointer types
The pointed-to type determines the type of a dereferenced value and the step size for pointer arithmetic.
int x=5,y=9;
int *p=&x;
int *q=p;
q=&y;

Initially q points to x, like p. Assigning &y to q does not change p, x or y. Declaration trap: int *p, q; declares p as a pointer and q as an int. Use int *p, *q; for two pointers.
Null and validity
A null pointer does not reference an object. Initialize an unused pointer to NULL when appropriate and test before dereferencing.
int *p=NULL;
if(p!=NULL)
printf(“%d”,*p);
| State | Meaning |
|---|---|
| Valid | References live object |
| Null | No object |
| Uninitialized | Value not set |
| Dangling | Target lifetime ended |
Non-null does not guarantee validity. The pointee must still be alive and correctly typed. A pointer to a local automatic object becomes invalid after the object lifetime ends.
Never return the address of an automatic local object.
Exam Check
Why must int *p be initialized before use? Answer: The declaration does not establish an address of a live object.
Pointer type qualifiers
The location of const in a pointer declaration changes what may be modified through that declaration.
| Declaration | Meaning |
|---|---|
| const int *p | Read-only integer through p |
| int *const p | Fixed pointer, writable integer |
| const int *const p | Fixed pointer, read-only through p |
int x=10,y=20;
const int *a=&x;
a=&y;
int *const b=&x;
*b=15;
The pointer a may change its stored address, but writing *a through that pointer is not allowed. The pointer b must keep its initialized address, but the referenced integer x may change. After these statements, x is 15, y is 20 and a points to y.
Note: A pointer to const data does not guarantee the original object is immutable through every other access path.
Generic object pointers
void * can hold a pointer to an object of any object type, subject to the language’s conversion rules. It cannot directly be dereferenced to obtain a typed value. Convert back to a compatible object pointer first.
int n=42;
void *v=&n;
int *q=v;
printf(“%d”,*q);
Output: 42. Standard C does not provide arithmetic on void * because void has no element size. Use a compatible typed pointer for traversal.
13. Pointer arithmetic and arrays
Moving through arrays
An array expression normally converts to a pointer to the first element.
int a[4]={10,20,30,40};
int *p=a;
printf(“%d”,*(p+2));

Output: 30. a[i] equals *(a+i). Adding one to an int pointer advances by sizeof(int), not one byte.
If the base is 1000 and int occupies four bytes, p+2 points to 1008 within the array.
The pointer variable can be incremented; the array name cannot be reassigned.
Allowed arithmetic
| Expression | Meaning |
|---|---|
| p+1 | Next element |
| p-1 | Previous element when valid |
| p++ | Advance pointer |
| q-p | Distance in elements |
| p==q | Equality |
Arithmetic must remain within the same array object or produce its one-past-end pointer. The one-past pointer is not dereferenced.
for(int *p=a;p<a+4;p++)
printf(“%d “,*p);
Output: 10 20 30 40.
Adding two pointers or multiplying pointers is invalid. The difference of pointers into one array has type ptrdiff_t.
Exam Check
If p points to a[1] and q points to a[4], what is q−p? Answer: 3 elements, assuming both belong to the same array.
Pointer expression precedence
Parentheses help distinguish operations on the pointer itself from operations on the pointed-to value.
| Expression | Interpretation |
|---|---|
| *p++ | Read current element then advance p |
| (*p)++ | Increment pointed-to value |
| *++p | Advance p then dereference |
| ++*p | Increment pointed-to value first |
| *(p+2) | Read element two positions ahead |
int a[]={10,20,30};
int *p=a;
int first=*p++;
int old=(*p)++;
int next=*++p;
Trace: first=10, p then points to a[1]; old=20 and a[1] becomes 21; next=30 and p points to a[2]. The final array is {10,21,30}.

Never combine multiple unsequenced modifications of a single object in an expression. Keep changes in separate statements to make the program easier to verify.
Pointer difference
#include <stddef.h>
int a[6]={0};
int *p=a+1,*q=a+5;
ptrdiff_t d=q-p;
The difference is 4 elements, not 4 bytes. If int is four bytes, the corresponding addresses differ by 16 bytes. Subtraction is defined when pointers refer to elements of the same array (including one-past) and the result is representable in ptrdiff_t.
14. Call by reference using pointers
Passing an address
C passes all arguments by value. Reference-like behavior is achieved by passing an object address and dereferencing it inside the function.
void change(int *p){
*p=100;
}


Call change(&x). The function receives a copy of the address; both refer to the same x. Reassigning p itself does not change a caller pointer.

Program: swap
#include <stdio.h>
void swap(int *a,int *b){
int t=*a;
*a=*b;
*b=t;
}
int main(void){
int x=10,y=20;
swap(&x,&y);
printf(“%d %d”,x,y);
return 0;
}
Output: 20 10.
| Stage | x | y |
|---|---|---|
| Initially | 10 | 20 |
| *a=*b | 20 | 20 |
| *b=t | 20 | 10 |
Passing x and y without addresses would only give the function copies of the integers. Passing addresses lets it modify the original objects.
Exam Check
Why does swapping two ordinary integer parameters not swap caller variables? Answer: They are copies; their addresses must be passed for indirect updates.
15. Passing arrays and pointers to functions
Array parameter adjustment
A parameter declared int a[] adjusts to int *a. Pass the element count separately because the function receives no automatic size information.
int sum(const int a[],int n){
int s=0;
for(int i=0;i<n;i++)
s+=a[i];
return s;
}
sum(values,4) reads four elements. const prevents modification through the parameter.
void clear(int a[],int n){
for(int i=0;i<n;i++)
a[i]=0;
}
sizeof a inside either function gives pointer size, not the original array size.

Passing a matrix
A 2D array argument converts to a pointer to its first row, not int **. The parameter must describe row width.
void show(int a[][3],int rows){
for(int i=0;i<rows;i++){
for(int j=0;j<3;j++)
printf(“%d “,a[i][j]);
puts(“”);
}
}
| Parameter | Interpretation |
|---|---|
| int a[] | int *a |
| int a[][3] | int (*a)[3] |
| const int *a | Read through pointer |
On VLA-capable implementations a runtime width can be passed before the array parameter:
void show(int r,int c,int a[r][c]);
Exam Check
Why is the array count passed to sum()? Answer: The adjusted pointer parameter contains no array-length information.
Returning two results through pointer parameters
A function has one return value, but it can supply additional results through addresses of output objects. For a nonempty input array, write the minimum and maximum to two caller-owned integers.
#include <stdio.h>
void limits(const int a[],int n,
int *lo,int *hi){
*lo=*hi=a[0];
for(int i=1;i<n;i++){
if(a[i]<*lo)*lo=a[i];
if(a[i]>*hi)*hi=a[i];
}
}
int main(void){
int a[]={8,3,12,7};
int min,max;
limits(a,4,&min,&max);
printf(“%d %d”,min,max);
return 0;
}
Output: 3 12.
| Read | Min | Max |
|---|---|---|
| 8 | 8 | 8 |
| 3 | 3 | 8 |
| 12 | 3 | 12 |
| 7 | 3 | 12 |
The parameters lo and hi must refer to separate valid output objects. The input cannot be empty because the function reads a[0]. Mark the read-only array parameter const to express the intended contract.
Parameter interface checklist
State element count, mutability, expected pointer validity and return meaning. For a routine that may fail, use its return value to report success and keep result values in output parameters. Document whether incoming ranges may overlap.
16. Array of pointers and pointer to array
Array of pointers
An array can contain pointer values. Each value may reference a different compatible object.
int x=11,y=22,z=33;
int *p[3]={&x,&y,&z};
printf(“%d”,*p[1]);

Output: 22. The elements are pointers, not copies of the integers. Each pointer can be reassigned independently.
This representation is useful for collections of addresses, such as references to strings of different lengths.
Pointer to array
Parentheses change the meaning. int (*p)[3] is one pointer to a row of three integers.
int a[2][3]={{1,2,3},{4,5,6}};
int (*p)[3]=a;
printf(“%d”,p[1][2]);
Output: 6. Incrementing p moves across an entire row.
| Array of pointers | Pointer to array |
|---|---|
| int *p[3] | int (*p)[3] |
| Three pointer objects | One pointer object |
| p[i] is int * | p[i] is array |
| Targets may differ | Targets same-width rows |
Memory trick: brackets bind more tightly than *; parentheses force grouping.
Exam Check
Interpret float *ptr[5] and float (*row)[5]. Answer: The first declares 5 pointers. The second declares one pointer to a five-float array.
Pointer arrays as indirect access tables
Consider three temperature readings stored in distinct variables. An array of three pointers can store addresses in any desired order without rearranging the actual variables.
int a=17,b=25,c=19;
int *order[]={&b,&c,&a};
for(int i=0;i<3;i++)
printf(“%d “,*order[i]);
Output: 25 19 17.

If *order[2]=20 is executed, a becomes 20. Changing order[2] itself to &b redirects that pointer and does not change a. Distinguish assignment to a pointer from assignment through the pointer.
Reading a matrix using row pointers
int a[3][2]={{1,2},{3,4},{5,6}};
int (*row)[2]=a;
for(int i=0;i<3;i++){
printf(“%d %d\n”,
row[i][0],row[i][1]);
}
Here row is a single pointer to an array of two integers. Adding one to row advances by one row. The array remains rectangular; each row has the same width.
| Expression | Result type |
|---|---|
| row | Pointer to two-int array |
| row[0] | Array of two int |
| row[0][1] | int value |
| row+1 | Pointer to next row |
Use parentheses in a declaration to express a pointer to an array; omitting them declares an array of pointers instead.
17. Pointer to pointer
Two levels of indirection
A pointer to pointer stores the address of another pointer object.
int x=50;
int *p=&x;
int **q=&p;
printf(“%d”,**q);

Output: 50. q has type int **, *q has type int *, and **q has type int.
**q=60;
This changes x to 60. Assigning *q = &y changes the stored value of p when y is a live integer.
A pointer to pointer can allow a function to update a caller pointer itself.
Redirect a pointer
void redirect(int **target,
int *new_value){
*target=new_value;
}
int main(void){
int x=10,y=20;
int *p=&x;
redirect(&p,&y);
return *p==20 ? 0:1;
}
After the call, p points to y.
| Expression | Type |
|---|---|
| q | int ** |
| *q | int * |
| **q | int |
| &q | int *** |
Do not confuse int ** with a pointer to a fixed-width row such as int (*)[3]. Their types, representations and indexing rules differ.
Exam Check
Given int **q=&p; what does *q=&y change? Answer: It changes p to reference y, assuming y is a live int.
18. Pointers to functions
Function pointer
A function pointer refers to a function with a compatible signature. It allows selection of behavior at runtime.
int add(int a,int b){
return a+b;
}
int (*op)(int,int)=add;
Parentheses around *op are necessary. op points to a function taking two integers and returning an integer.
int result=op(3,4);
Result: 7. The alternative syntax (*op)(3,4) is equivalent.
Do not call through an incompatible function pointer. Function pointers are not ordinary object pointers.
Pass a function pointer
#include <stdio.h>
int add(int a,int b){return a+b;}
int mul(int a,int b){return a*b;}
int compute(int x,int y,
int (*fn)(int,int)){
return fn(x,y);
}
int main(void){
printf(“%d “,compute(3,4,add));
printf(“%d”,compute(3,4,mul));
return 0;
}
Output: 7 12

compute receives a compatible pointer. Its interface can apply different operations to the same values.
Exam Check
What is the return type of int (*fn)(int,int)? Answer: int. The referenced function accepts two int arguments.
Function-pointer dispatch table
An array of compatible function pointers can represent several alternative operations. Select a function by a verified index. This pattern separates the selection of a behavior from its execution.
#include <stdio.h>
int inc(int n){return n+1;}
int dbl(int n){return n*2;}
int sq(int n){return n*n;}
int main(void){
int (*op[3])(int)={inc,dbl,sq};
int choice=2,value=5;
if(choice>=0 && choice<3)
printf(“%d”,op[choice](value));
return 0;
}
Output: 25.
| Index | Function | Input 5 |
|---|---|---|
| 0 | inc | 6 |
| 1 | dbl | 10 |
| 2 | sq | 25 |
The declaration binds brackets before the dereference inside parentheses: op is an array of three pointers, each pointing to a function taking an int and returning an int. All stored function pointers must have compatible function types.
Typedef for readable declarations
typedef int (*Unary)(int);
Unary actions[3]={inc,dbl,sq};
int ans=actions[1](7);
ans becomes 14. The alias Unary describes a pointer type, not a function object. The function name in an expression ordinarily converts to a function pointer.
Exam tip: int (*f)(int) denotes a pointer to function, whereas int *f(int) declares a function returning a pointer to int.
19. Strings: representation and initialization
Null-terminated characters
A C string is a sequence of characters followed by a null character, written \0, usually stored in a char array.
char s[]=”CAT”;
char t[4]={‘C’,’A’,’T’,’\0′};

These declarations represent the same string. The terminator takes one extra character beyond the visible text.
A character constant ‘A’ represents a character. The literal “A” contains A and a null character.
String literals must not be modified.

Length and capacity
| Declaration | Capacity | Length |
|---|---|---|
| char a[]=”Hi” | 3 | 2 |
| char b[8]=”Hi” | 8 | 2 |
| char c[1]=”” | 1 | 0 |
Capacity counts all allocated elements. Length counts characters before the first null.
char text[8]=”Hello”;
text[0]=’Y’;
The string becomes “Yello”. Use char s[] = “Hello” for a writable copy; use const char *s = “Hello” for a read-only view.
An unterminated char array is not a valid C string. Reserve one extra slot for the ending null.
Exam Check
How much capacity is needed for the string NOTES? Answer: At least six char elements: five visible letters and the null.
20. Accessing strings and input
Character access
Visit characters until the null terminator.
char s[]=”C language”;
int count=0;
for(int i=0;s[i]!=’\0′;i++)
count++;
count is 10, including the space.

To edit, assign to a valid position of a writable char array. printf(“%s”,s) prints up to the null terminator; puts(s) also prints a newline.
Do not access beyond an array or assume that a char array is terminated.
Reading words and lines
A field width limits scanf string input. A buffer of 20 chars can store 19 visible chars plus a null.
char word[20];
if(scanf(“%19s”,word)==1)
puts(word);
fgets reads a line containing spaces within the specified capacity.
char line[80];
if(fgets(line,sizeof line,stdin))
puts(line);
A successful fgets may retain a newline. It can be removed using string.h:
line[strcspn(line,”\n”)]=’\0′;
Perform this only after successful input. Never use gets, which cannot enforce capacity.
Exam Check
What does scanf(“%9s”,buf) require of buf? Answer: A writable array with room for at least ten characters including the terminator.
Character classification and line processing
Count uppercase letters, lowercase letters, digits and other characters in a string. Use ctype.h classification functions, passing either EOF or an unsigned-char value as required by those functions.
#include <stdio.h>
#include <ctype.h>
int main(void){
char s[]=”C Lab 2025″;
int upper=0,lower=0,digit=0,other=0;
for(int i=0;s[i];i++){
unsigned char c=s[i];
if(isupper(c))upper++;
else if(islower(c))lower++;
else if(isdigit(c))digit++;
else other++;
}
printf(“%d %d %d %d”,
upper,lower,digit,other);
return 0;
}
Output: 2 2 4 2.
| Group | Members | Count |
|---|---|---|
| Uppercase | C,L | 2 |
| Lowercase | a,b | 2 |
| Digits | 2,0,2,5 | 4 |
| Other | Two spaces | 2 |
This approach is more portable than assuming all character sets use consecutive numeric letter codes. The loop stops at the first null character.
Remove a trailing newline
Successful fgets may store a newline if it fits in the buffer. Find that newline before performing further comparisons. Strip it if present, but do not assume the input always contains one. A long line may require subsequent reads.
21. Arrays of strings
Character matrix
A two-dimensional char array stores multiple writable strings in equally sized rows.
char names[3][10]={
“Asha”,”Ravi”,”Neha”
};

Each row can hold nine visible characters plus a terminator. names[1] is the second string; names[1][0] equals R.
for(int i=0;i<3;i++)
puts(names[i]);
This matrix allocates 30 chars regardless of individual name lengths.
Array of string pointers
A pointer array can reference strings of various lengths.
const char *names[]={
“Asha”,”Ravi”,”Neha”
};
The array contains three pointers to string literals. Do not modify the literals.
| Character matrix | Pointer array |
|---|---|
| Fixed row capacity | Independent targets |
| Writable rows | Literals read-only |
| Contiguous characters | Contiguous pointers |
| Suitable for editing | Suitable for fixed labels |
The two declarations have different types. Choose a representation according to the required operations.
Exam Check
How many chars does char names[4][12] allocate? Answer: 48, with a maximum of eleven visible characters per row.
Order an array of string references
String content must be compared lexicographically, rather than by the addresses of character arrays. A collection of pointers to immutable string literals can be rearranged without copying individual text sequences.
#include <stdio.h>
#include <string.h>
int main(void){
const char *a[]={“Ravi”,”Asha”,”Mina”};
for(int i=0;i<2;i++)
for(int j=i+1;j<3;j++)
if(strcmp(a[i],a[j])>0){
const char *t=a[i];
a[i]=a[j]; a[j]=t;
}
for(int i=0;i<3;i++)puts(a[i]);
return 0;
}
Output: Asha, Mina, Ravi (one per line).
| Step | Pointer order |
|---|---|
| Initial | Ravi, Asha, Mina |
| First swap | Asha, Ravi, Mina |
| Second swap | Asha, Mina, Ravi |
Only pointer variables are swapped. The characters belonging to string literals are not modified.
Rectangular character storage
When storing input names in char names[4][16], each of four rows has a fixed capacity of 16 characters. The usable text length of each row is at most 15. Read or copy into each row with its own capacity check. If full names include spaces, line-based input is more convenient than a single-word scan.
22. Passing strings to functions
Read-only string parameter
Pass a pointer to the first character. Use const char * for a function that only reads.
int length(const char *s){
int n=0;
while(s[n]!=’\0′)n++;
return n;
}
length(“AKTU”) returns 4. The parameter requires a valid null-terminated string.
To modify a caller string, accept char * and ensure the operation fits the destination capacity.
void change_first(char *s){
if(*s!=’\0′) *s=’X’;
}
The caller must pass writable storage. A string function receives an address, not an automatic capacity.

Destination buffer and capacity
A copy function must reserve space for the null terminator.
#include <stddef.h>
int copy_text(char *out,size_t cap,
const char *in){
size_t i=0;
if(cap==0)return 0;
while(i<cap-1 && in[i]){
out[i]=in[i];
i++;
}
out[i]=’\0′;
return in[i]==’\0′;
}
Returns 1 when the entire string fits, otherwise 0 with a truncated but terminated result. Assumes nonoverlapping valid buffers.
Exam point: pass destination capacity explicitly.
Exam Check
Why declare a reading function parameter const char *? Answer: To prevent writes to the referenced characters through that parameter.
23. Standard string functions
Header string.h
The standard header declares functions for manipulating null-terminated strings.
| Function | Purpose |
|---|---|
| strlen(s) | Length before null |
| strcpy(d,s) | Copy including null |
| strcat(d,s) | Append string |
| strcmp(a,b) | Lexicographic comparison |
| strchr(s,c) | Find first character |
| strstr(s,t) | Find first substring |
strlen returns size_t and can be printed using %zu. strcmp returns a negative value, zero or a positive value, not necessarily −1 or +1.
strcpy and strcat require adequate destination capacity, including the null.
Worked examples
#include <stdio.h>
#include <string.h>
int main(void){
char a[20]=”Hello”;
char b[]=” C”;
strcat(a,b);
printf(“%s “,a);
printf(“%zu “,strlen(a));
printf(“%d”,strcmp(“C”,”C”));
return 0;
}
Output: Hello C 7 0
strncpy copies up to n characters but may leave the result unterminated if the source is too long. It is not a universal safe substitute for strcpy.
strncat limits appended source characters, not total capacity. Calculate remaining room carefully.
Exam Check
What is strlen(“Hello”) and sizeof “Hello”? Answer: 5 and 6. sizeof includes the null terminator.
Implement string comparison manually
The result of a lexicographic comparison is determined by the first differing character or by which sequence ends first. Compare characters as unsigned char values.
int compare(const char *a,
const char *b){
while(*a && *a==*b){
a++;b++;
}
unsigned char x=*a,y=*b;
return (x>y)-(x<y);
}
The return value is -1, 0 or 1 in this particular implementation. Standard strcmp only guarantees a negative, zero or positive result.
| Pair | Result |
|---|---|
| CAT, CAT | 0 |
| CAT, CAR | Positive |
| BAT, CAT | Negative |
| CAT, CATS | Negative |
Find a substring
#include <stdio.h>
#include <string.h>
int main(void){
const char s[]=”C programming”;
const char *p=strstr(s,”gram”);
if(p)printf(“%td”,p-s);
else puts(“Not found”);
return 0;
}
Output: 5. The substring begins at zero-based index 5. strstr returns a pointer to the first match, or a null pointer when there is no match. The pointer difference is meaningful because a successful match lies within the same string array.
Copy and append planning
Before appending a source string of length m to a destination containing n characters, the destination needs capacity at least n+m+1. For length 4 and append length 6, the minimum capacity is 11. A capacity of 10 is insufficient because it leaves no slot for the null terminator.
24. Worked string programs
Count vowels
Use the standard ctype function to handle letter case.
#include <stdio.h>
#include <ctype.h>
int main(void){
char s[]=”Education”;
int n=0;
for(int i=0;s[i];i++){
int c=tolower((unsigned char)s[i]);
if(c==’a’||c==’e’||c==’i’||
c==’o’||c==’u’)n++;
}
printf(“%d”,n);
return 0;
}
Output: 5. E, u, a, i and o are vowels in Education. A full traversal of n characters takes O(n) time.
Palindrome check
#include <stdio.h>
#include <string.h>
int main(void){
char s[]=”madam”;
size_t n=strlen(s);
int ok=1;
for(size_t i=0;i<n/2;i++){
if(s[i]!=s[n-1-i]){
ok=0;break;
}
}
puts(ok?”Palindrome”:”No”);
return 0;
}
Output: Palindrome.

Compare only matching positions from opposite ends. This definition treats case and spaces literally.
Exam Check
Could the palindrome program check the word level? Answer: Yes. Compare l with l, e with e; the middle v needs no comparison.
Count words in a line
Words are considered nonempty groups of non-whitespace characters. Count each transition from whitespace to a non-whitespace character. Multiple neighboring spaces do not create extra words.
#include <stdio.h>
#include <ctype.h>
int main(void){
char s[]=” C is fun “;
int words=0,inword=0;
for(int i=0;s[i];i++){
if(isspace((unsigned char)s[i]))
inword=0;
else if(!inword){
++words;inword=1;
}
}
printf(“%d”,words);
return 0;
}
Output: 3.
| Group | State | Count |
|---|---|---|
| Leading spaces | Outside | 0 |
| C | Enter word | 1 |
| Spaces | Outside | 1 |
| is | Enter word | 2 |
| Space | Outside | 2 |
| fun | Enter word | 3 |
Convert a writable string to uppercase
#include <ctype.h>
void uppercase(char *s){
for(;*s;s++)
*s=(char)toupper((unsigned char)*s);
}
For a writable array containing “Hello C”, the function produces “HELLO C”. The terminator remains untouched because the loop tests *s before performing an assignment. This function must receive writable, properly terminated storage.
Exam practice: Modify the word-count method to find the length of the longest word. Keep a current length, reset it on whitespace, and update a maximum whenever the current length grows.
EXAM QUESTIONS WITH ANSWERS
Practice questions covering the definitions, comparisons and applications in Unit III.
Short-answer practice
Q1. What is an array?
Answer. An array is a collection of elements of the same type arranged contiguously. An integer index identifies an element, beginning at zero in C.
Q2. Why are array elements indexed from zero?
Answer. The index specifies an element offset from the beginning. Index zero selects the first element without advancing from the array’s base address.
Q3. State the syntax of a one-dimensional array.
Answer. Write data_type name[count]; for example, int marks[6]; declares an array with six integer elements and valid indices 0 through 5.
Q4. What is partial array initialization?
Answer. An initializer may specify fewer values than the array’s declared length. The remaining elements receive zero initialization, as in int a[4]={7,8}.
Q5. Can an entire array be assigned using =?
Answer. No. Use individual element assignments or a suitable copying operation. Initializer lists at declaration are different from assigning to an existing array object.
Q6. How is array capacity different from length?
Answer. Capacity is the number of slots available. Logical length is the number currently containing meaningful data; it must not exceed the allocated capacity.
Q7. What is a variable-length array?
Answer. A block-scope array with a positive bound evaluated at runtime on implementations supporting VLAs. Its extent does not automatically change when the bound variable changes.
Q8. What is a two-dimensional array?
Answer. An array whose elements are themselves arrays of equal width. For int a[3][4], there are three rows with four integer elements in each.
Q9. Explain row-major representation.
Answer. C stores consecutive elements within a row, followed by the next row. A[i][j] has element offset i × column_count + j.
Q10. How is a three-dimensional index calculated?
Answer. For A[X][Y][Z], its element offset at [i][j][k] is (i × Y + j) × Z + k; multiply by the element size for the byte offset.
Q11. What is a pointer?
Answer. A typed value that can refer to an object or function. A valid object pointer provides indirect access to the referenced object.
Q12. Distinguish & and * in pointer expressions.
Answer. Unary & obtains an object’s address where permitted. Unary * dereferences a valid pointer and designates the object it references.
Q13. What is a null pointer?
Answer. A pointer value that does not designate an object or function. Testing for null is useful, but a non-null pointer must also refer to a valid live target.
Q14. What is pointer arithmetic?
Answer. Adding or subtracting an integer moves by elements of the pointed-to type within an array. The one-past position can be formed but not dereferenced.
Q15. Does C provide true call by reference?
Answer. C passes argument values. Passing an object’s address allows the callee to modify the referenced object, giving reference-like behavior.
Q16. Why pass an array’s length to a function?
Answer. An array parameter adjusts to a pointer parameter. The pointer does not carry the original array’s element count, so pass the required length separately.
Q17. Array of pointers versus pointer to an array?
Answer. int *p[3] declares three pointers to int, whereas int (*p)[3] declares one pointer to an array of three integers.
Q18. What is a pointer to pointer?
Answer. A pointer whose referenced object is another pointer. For int **q, *q is an int pointer and **q designates the integer when all references are valid.
Q19. What is a function pointer?
Answer. A pointer referring to a function of a compatible signature. int (*f)(int) can refer to a function taking and returning int.
Q20. How is a C string represented?
Answer. Characters are stored in a char sequence followed by a null character, written \0. A string of five visible characters needs at least six slots.
Q21. Differentiate strlen and sizeof.
Answer. strlen counts characters before the terminator. sizeof measures the complete object in bytes, which may include unused array capacity and the terminator.
Q22. How can a list of strings be stored?
Answer. Use fixed-width rows in a two-dimensional char array or an array of pointers to separate strings. Their layout and mutability characteristics differ.
Q23. Why pass string capacity to a function?
Answer. A destination pointer does not describe available storage. A capacity argument allows the function to check room for copied characters and the terminating null.
Q24. What does strcmp return?
Answer. A negative value when the first string precedes the second, zero for equal contents, or a positive value when the first follows the second.
Structured long-answer practice
Use a clear definition, numbered explanation, examples and relevant comparisons. Adjust the depth of your answer to the marks and question.
Long question 1. Explain one-dimensional arrays, initialization and array operations.
Answer
-
1. Definition and declaration. An array consists of same-type elements in contiguous storage. int a[5]; declares five integer elements and supplies valid subscripts 0 through 4. Its size in bytes is five times sizeof(int).
-
2. Initialization. An initializer list supplies starting values in declaration order. int a[5]={2,4}; initializes the first two elements and gives zero to the remaining three. A dimension can be inferred when an initializer determines it.
-
3. Access and traversal. Use a[i] to select position i. A for loop starting at zero and ending before the element count visits each valid entry. The same traversal can accept input or display data.
-
4. Manipulation. For insertion within spare capacity, shift entries right from the end; deletion shifts later entries left. Maintain the logical length and avoid indices beyond the available region.
-
5. Illustration and safeguards. If four-byte values begin at 1000, a[3] begins at 1012. Use a valid index and initialize automatic elements before reading them. An array’s capacity is fixed for its lifetime.
Long question 2. Explain two-dimensional and multidimensional arrays with memory representation.
Answer
-
1. Declaration. int m[2][3] declares two rows of three integers. Each element of the outer array is a row array, and the total number of integer elements is six.
-
2. Initialization. Braces group values by row, for example {{1,2,3},{4,5,6}}. The expression m[1][2] selects the third entry in the second row, giving 6.
-
3. Storage calculation. Rows are stored successively. For R rows, C columns and width w, the byte address of A[i][j] is B+(i×C+j)×w under the stated address assumptions.
-
4. Operations. Use nested loops to access rows and columns. Matrix addition requires equal shapes. Multiplication uses a common inner dimension; transpose exchanges row and column indices.
-
5. Higher dimensions. For A[X][Y][Z], the offset is ((i×Y+j)×Z+k)×w. Check all three subscripts separately. Such arrays can represent layers, rows and columns.
Long question 3. Explain pointer declaration, operations and pointer arithmetic.
Answer
-
1. Meaning. A pointer stores a typed reference to a target. In int x=7; int *p=&x;, p holds the address of x, while *p designates x.
-
2. Operators. Unary & obtains the address of an eligible object; unary * accesses the referenced value. Assigning *p=9 modifies x. Changing p instead changes its reference.
-
3. Types and validity. Use a compatible pointer type and a live object. A null pointer has no referenced object; a pointer to an expired local object cannot be used to access it.
-
4. Arithmetic. For a pointer into an array, p+1 advances by one element. Differences of eligible pointers within the same array count elements, not bytes. A one-past pointer is useful as a boundary.
-
5. Example. Given int a[]={5,10,15}; int *p=a;, *(p+2) is 15. Keep arithmetic in the same array and never dereference the one-past position.
Long question 4. Explain reference-like argument passing, pointer arrays and function pointers.
Answer
-
1. Argument values. C passes values. To change a caller’s object, supply its address as an argument; a compatible pointer parameter can then modify the original.
-
2. Swap example. For a swap routine receiving int *x and int *y, save *x temporarily, assign *x=*y and assign *y the saved value. Call with addresses of two valid integers.
-
3. Array parameters. A function parameter written int a[] adjusts to int *a. Supply the count as a separate parameter. A two-dimensional array parameter must also describe the row width.
-
4. Pointer arrays. int *p[3] represents three pointer slots, whereas int (*p)[3] denotes a pointer to a three-integer row. An int ** parameter can modify a caller pointer itself.
-
5. Function pointers. int (*op)(int,int) points to a compatible function returning int. Assign a matching function and invoke op(2,3). This allows behavior to be selected at runtime.
Long question 5. Discuss string initialization, access, input and arrays of strings.
Answer
-
1. Representation. A string is a sequence of characters ending at the first null character. char word[]=”CAT” has four character slots, including the terminator.
-
2. Initialization and modification. A char array initialized from a literal is writable. A pointer to a string literal does not authorize modifying that literal. Match access rules to the actual storage.
-
3. Character traversal. Starting from index zero, continue until the null character. An ordinary character array may lack a terminator; then standard string-processing routines are not appropriate.
-
4. Input. Use a width-limited word conversion for scanf or bounded fgets for text containing spaces. Check success before processing. Account for a retained newline when appropriate.
-
5. Collections and functions. Fixed-width char rows support writable strings with common capacity; an array of pointers can reference different strings. Pass the destination capacity for functions that write text.
Long question 6. Explain important string library functions with suitable examples.
Answer
-
1. Header and length. Include string.h for declarations. strlen returns the number of characters before the first null as size_t; it does not report total array capacity.
-
2. Copying. strcpy copies a terminated source including its null into valid destination storage. The destination must have enough capacity and satisfy overlap restrictions.
-
3. Appending. strcat locates the destination terminator and appends the source. Reserve combined visible length plus one for the final null. Limit operations according to actual capacity.
-
4. Comparison and searching. strcmp reports negative, zero or positive according to ordering. strchr finds a requested character; strstr finds a matching substring, returning a pointer or null as appropriate.
-
5. Example and precautions. For char a[16]=”Hello”;, appending ” C” yields “Hello C” with length 7. Check capacity, termination and mutability; never assume strncpy always produces a terminated string.
QUICK REVISION AND KEY FORMULAS
| Topic | Recall |
|---|---|
| 1D address | B + i × w |
| 2D address | B + (i × C + j) × w |
| 3D offset | ((i × Y + j) × Z + k) × w |
| Valid array index | 0 through n-1 |
| Pointer arithmetic | Moves by element width |
| Array parameter | Pass element count separately |
| String storage | Visible length + 1 |
Key declarations
int a[5];
int matrix[2][3];
int *p=&a[0];
int *ptrs[3];
int (*row)[3];
int **q;
int (*fn)(int,int);
char text[16]=”C”;
Memory trick: Brackets bind more tightly than the asterisk. Parentheses change the declaration’s grouping.
String functions
| Function | Purpose |
|---|---|
| strlen | Visible character count |
| strcpy | Copy including terminator |
| strcat | Append |
| strcmp | Compare content |
| strchr | Find character |
| strstr | Find substring |
Solved revision numericals
-
1. A[4][6] with base 1000 and four-byte elements: A[2][4] lies at 1000+(2×6+4)×4=1064.
-
2. For int a[]={5,8,11,14}; int *p=a+1;, p[1] is 11 and p[-1] is 5. Both positions lie inside the original array.
-
3. char s[10]=”ABC”; s[1]=’\0′; gives strlen(s)=1 and sizeof s=10 bytes.
Practice program: pointer traversal
#include <stdio.h>
int main(void){
int a[]={2,4,6,8},total=0;
for(int *p=a;p<a+4;p++)
total+=*p;
printf(“%d”,total);
return 0;
}
Output: 20. The loop reads each element once.
Common mistakes
| Mistake | Correction |
|---|---|
| Array index n | Stop at n-1 |
| Uninitialized pointer | Set valid target |
| Copy too much text | Check capacity |
| Compare strings with == | Use strcmp |
Final checklist: Explain dimensions, indexing, memory, indirect access, function parameters and null termination before writing a program.