Module 4 · 16 min read · Free chapter
Arrays, strings and pointers
The address of a[i] is base + i × size, and a 2-D array is stored row by row. A string ends with '\0', so sizeof("GATE") is 5 but strlen is 4. Pointer arithmetic moves by whole elements. An array name decays to a pointer except with sizeof and &, and *p++ moves the pointer while (*p)++ changes the value.
Start from zero: house numbers and the dabba slip
Picture a long street of identical houses, each with a number painted on the gate: 2000, 2004, 2008 and so on. Every house holds one thing, such as a value. Memory in a computer is exactly such a street, and the house number is called an address.
Now think of a dabba delivery man. He does not carry the house; he carries a slip of paper with the house number written on it. That slip is a pointer: a variable whose value is an address, so that following it takes you to the real thing.
An array is a row of neighbouring houses given to one family, all of the same size. If you know where the first house is and how wide each house is, you can walk straight to the fifth one. A string is just an array of characters with a special "end of text" mark after the last letter.
Why it matters. Arrays, strings and pointers are where C is most powerful and most dangerous. GATE asks more output questions on pointers than on any other part of C.
One-dimensional arrays and address arithmetic
int a[5]; reserves five ints side by side, numbered a[0] to a[4]. Because the elements are contiguous, the address of any element is a simple formula:
where B is the base address and w is the size of one element. With and 4-byte ints, a[3] sits at . This is why indexing starts at 0: the index is the distance from the start.
int a[5] = {10, 20, 30}; /* a[3] and a[4] become 0 */
printf("%d %d %zu %zu\n", a[3], a[4], sizeof(a), sizeof(a) / sizeof(a[0]));
/* prints 0 0 20 5 */
A partial initialiser fills the remaining elements with 0, so int arr[4] = {0}; sets all four to 0. The expression sizeof(a) / sizeof(a[0]) gives the element count, 5 here, but only where a is visible as an array.
C performs no bounds checking. Writing a[5] = 1 compiles silently and is undefined behaviour: it may overwrite another variable, crash, or appear to work. Valid indices are always 0 to .
Why it matters. Constant-time access by index is what makes arrays the base of tables, buffers and matrices. The missing bounds check is also behind the buffer-overflow attacks that still trouble real software.
Two-dimensional arrays
A 2-D array such as int m[3][4] is an array of 3 rows, each an array of 4 ints. Memory is one long line, so C lays the rows end to end. This is row-major order: all of row 0, then all of row 1, then row 2.
For int a[R][C] with base address B and element size w, the address of a[i][j] is
because i full rows of C elements come first, then j more elements. With , and , m[2][1] is at . Our program measured the gap from m[0][0] to m[2][1] as 36 bytes, which matches.
The pointer view is just as important. m[i] is row i, which decays to a pointer to its first int, so m[i][j] is the same as *(*(m + i) + j). With values 1 to 12 filled row by row, m[1][2] printed 7 and *(*(m + 2) + 1) printed 10.
The type of m in an expression is "pointer to an array of 4 ints". So m + 1 jumps one whole row, which is 16 bytes, and that is why a function receiving the array must know the column count.
void print_row(int (*m)[4], int r) { /* or int m[][4] */
for (int j = 0; j < 4; j++) printf("%d ", m[r][j]);
} /* print_row(m, 1) printed 5 6 7 8 */
Why it matters. Images, game boards and DP tables are all 2-D arrays, and walking them row by row is much faster because of how caches load memory. GATE regularly asks for the address of an element in row-major or column-major order.
Strings and string functions
C has no separate string type. A string is a char array whose text ends with the null character '\0', which has the value 0. Every string function walks the array until it meets this mark.
char s[] = "GATE"; /* 5 bytes: G A T E \0 */
char *t = "GATE"; /* pointer to a string literal */
printf("%zu %zu %zu %zu\n", sizeof(s), strlen(s), sizeof(t), strlen(t));
/* prints 5 4 8 4 */
sizeof(s) counts the hidden '\0', so it is 5, while strlen(s) counts only the letters, so it is 4. For the pointer t, sizeof(t) is the size of a pointer, which was 8 on our machine. A char array built from separate characters {'h', 'i', '\0', 'x'} prints as "hi", because printing stops at the first '\0'.
The two declarations differ in a deeper way. char s[] = "hello"; makes a modifiable copy, so s[0] = 'j' turned it into "jello". But char *t = "GATE"; points at a string literal, and writing t[0] = 'D' is undefined behaviour; on many systems it crashes.
The main functions are in <string.h>.
strlen(s)counts the characters before'\0'.strcpy(d, s)copies s, with its'\0', into d.strcat(d, s)appends s to the end of d; withchar u[10] = "ab",strcat(u, "cd")gave "abcd" of length 4.strcmp(a, b)returns a negative value, 0 or a positive value when a comes before, equals or comes after b in character order.
None of these functions checks the size of the destination. If d is too small, they write past its end, which is undefined behaviour. Also remember that strcmp gives 0 for equal strings, so if (strcmp(a, b)) is true when the strings are different.
Why it matters. Names, PNR numbers and messages are all strings, and most C security holes are string copies into small buffers. GATE tests sizeof against strlen and pointer walks over strings very often.
Pointers and pointer arithmetic
A pointer is a variable that holds an address. int *p = &a; makes p hold the address of a, where & means "address of". Then *p means "the int at that address", so *p = 7 changes a itself.
Pointer arithmetic is scaled by the size of the pointed-to type. If p points to an int at address 2000, then p + 1 is 2004, not 2001, because the next int starts 4 bytes later. Our test confirmed that the byte gap between a + 1 and a was 4.
Subtracting two pointers into the same array gives the number of elements between them, of type ptrdiff_t. So &a[4] - &a[1] printed 3. Comparing pointers with < is meaningful only within one array.
A pointer that points nowhere should hold NULL. Dereferencing NULL, an uninitialised pointer or a pointer to freed memory is undefined behaviour, and in practice it usually crashes the program.
The busiest GATE trap combines * and ++. Postfix ++ binds tighter than unary *, so the three forms below do different things.
int a[5] = {10, 20, 30};
int *p = a;
int v1 = *p++; /* read 10, then move p to a[1] */
int v2 = *p; /* 20 */
int v3 = (*p)++; /* give 20, then a[1] becomes 21 */
int v4 = ++*p; /* a[1] becomes 22, give 22 */
printf("%d %d %d %d %d\n", v1, v2, v3, v4, a[1]); /* prints 10 20 20 22 22 */
The same idea walks a string. while (*q) q++; moves q to the '\0' of "hello", and q - str then gave 5, which is the length.
Why it matters. Pointers let functions share large data without copying it, and they are the links of every linked list and tree. Reading *p++ correctly is also essential for understanding standard library code.
Arrays versus pointers, and passing arrays
Arrays and pointers are closely linked but are not the same thing. In most expressions an array name decays into a pointer to its first element, so a behaves like &a[0]. In fact C defines a[i] as *(a + i), and since addition is commutative, even 2[a] is legal: with a = {10, 20, 30}, both *(a + 2) and 2[a] printed 30.
The decay does not happen in three places: as the operand of sizeof, as the operand of &, and when a string literal initialises a char array. That is why sizeof(a) gives the whole array, and why &a has a different type, "pointer to array of 5 ints". So &a + 1 jumps past the whole array: (int *)(&a + 1) - a printed 5.
An array is also not assignable. You can write p = a to make a pointer point at an array, but a = p does not compile, because an array name is not a variable that holds an address.
When you pass an array to a function, only the pointer is passed. A parameter written int a[] is really int *a, so inside the function sizeof(a) / sizeof(a[0]) gave 2 (an 8-byte pointer over a 4-byte int), not 5, and gcc warned about it. Always pass the length as a separate argument.
Because the function gets the address, it can change the caller's elements. The same trick gives call by reference for single variables.
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
int x = 1, y = 2;
swap(&x, &y);
printf("%d %d\n", x, y); /* prints 2 1 */
Why it matters. Passing a pointer instead of copying an array of a million elements saves both time and memory. Knowing where decay stops answers most sizeof questions in GATE.
Pointer to pointer, function pointers and const
A pointer to pointer holds the address of another pointer. With int a = 5; int *p = &a; int **pp = &p;, the expression *pp is p and **pp is a, so **pp = 7 changed a to 7. Its main use is letting a function change the caller's pointer: after setp(&p, &b) with *pp = t inside, p pointed to b and *p printed 9.
Arrays of strings use the same idea. char *c[] = {"GATE", "EXAM", "QUIZ"}; is an array of three pointers, and char **cp = c; points to its first element. Then *(cp + 1) is "EXAM", **cp is 'G' and *(*(cp + 2) + 1) is 'U', and the program printed "EXAM G U".
A function pointer stores the address of a function. It is declared with brackets around the name, because int *fp(int, int) would declare a function returning a pointer instead.
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int (*fp)(int, int) = add;
int (*ops[2])(int, int) = {add, mul};
printf("%d %d\n", fp(3, 4), ops[1](5, 6)); /* prints 7 30 */
Function pointers make callbacks possible: the library function qsort, for example, takes a pointer to your comparison function. Tables of function pointers are also used to build menus and simple interpreters.
const with pointers has three forms, and the trick is to read the declaration from right to left.
const int *preads "p is a pointer to a const int":*p = 5is an error, butp = &zis allowed.int *const preads "p is a const pointer to an int":p = 0is an error, but*p = 4is allowed.const int *const pfixes both the pointer and the value.
gcc reported "assignment of read-only location '*pc'" for the first kind of error and "assignment of read-only variable 'k'" for the second.
Why it matters. const documents which data a function promises not to touch, as in strlen(const char *s). Function pointers are how C achieves plug-in behaviour without objects.
Worked GATE-style pointer outputs
The safe method for any pointer question is to draw the array with indices, mark where each pointer stands, and move the arrow one step at a time. Here are three short programs whose outputs we compiled and ran.
Example 1: a moving pointer.
int a[] = {10, 20, 30, 40, 50};
int *p = a;
p++;
printf("%d %d %d %d\n", *p, *(p + 2), p[1], *p + 2); /* prints 20 40 30 22 */
After p++, p stands on index 1, which holds 20. Then *(p + 2) is index 3, which is 40, and p[1] is index 2, which is 30. Finally *p + 2 adds 2 to the value, giving 22, because * binds tighter than +.
Example 2: a pointer to a row.
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*rp)[3] = m;
printf("%d %d\n", (*(rp + 1))[2], *(*rp + 1)); /* prints 6 2 */
Here rp + 1 moves a whole row, so (*(rp + 1))[2] is row 1, column 2, which is 6. But *rp is row 0 decayed to an int pointer, so *rp + 1 moves one int, and its value is 2.
Example 3: pointer difference and characters.
int x[4] = {2, 4, 6, 8};
int *y = x + 1, *z = &x[3];
char s[] = "COMPUTER";
printf("%td %d %s\n", z - y, *y * *z, s + (s[3] - s[1])); /* prints 2 32 OMPUTER */
The pointers are two elements apart, so z - y is 2, and . In the string, s[3] is 'P' and s[1] is 'O', which differ by 1 in character code, so s + 1 prints from the second letter.
Why it matters. These patterns repeat in GATE year after year with new numbers. Drawing arrows takes ten seconds and removes almost every slip.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about this topic in four ways.
- They ask you to differentiate an array from a pointer, or
char s[]fromchar *s, with examples. - They ask you to explain pointer arithmetic and the address formula for 1-D and 2-D arrays, with a numerical.
- They ask you to write string functions such as length, copy, reverse or palindrome check without using
<string.h>. - They ask you to show call by reference with pointers, or to explain
constpointers and function pointers.
Practice questions (our own, not previous-year questions).
- Write a C function that reverses a string in place using two pointers, and trace it on "GATE". (10 marks)
- An array
int a[10][20]is stored from address 5000 with 4-byte integers. Find the address ofa[6][15]in row-major and in column-major order. (5 marks) - "An array name is not a pointer." Explain this statement with the help of
sizeof,&and assignment. (15 marks)
Answer plan for question 3.
- State that an array is a block of contiguous elements, while a pointer is a separate variable that stores an address.
- Explain that in most expressions the array name decays to a pointer to its first element, so
a[i]equals*(a + i). - Show the first exception:
sizeof(a)gives the size of the whole array, such as 20 bytes for five ints, whilesizeof(p)gives the pointer size. - Show the second exception:
&ais a pointer to the whole array, so&a + 1moves past all the elements. - Show that
p = ais legal buta = pis not, because an array cannot be assigned. - Conclude that an array parameter in a function is really a pointer, so the length must be passed separately.
Quick revision
- The address of
a[i]is , and indices run from 0 to with no bounds check. - A 2-D array is row-major, so
a[i][j]is at . - A string ends with
'\0', sosizeof("GATE")is 5 andstrlen("GATE")is 4. char s[]is a modifiable copy, while modifying the literal behindchar *pis undefined.strcmpreturns 0 for equal strings, and string functions never check the destination size.p + kmoves k elements, and the difference of two pointers counts elements.*p++moves the pointer,(*p)++changes the value and returns the old one, and++*preturns the new value.- An array name decays to a pointer except with
sizeof,&and a string initialiser. - An array parameter is a pointer, so pass the length separately.
- Passing
&xlets a function change x, which is how C simulates call by reference. - Read
constdeclarations right to left:const int *pfixes the value andint *const pfixes the pointer.