Computer Science and IT‹›⌂ 0:00 studied

Module 4 · 16 min read · Free chapter

Arrays, strings and pointers

In short

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.

What are you preparing for? We show the practice and previous year questions of your exam.

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:

address of a[i]=B+i×w\text{address of } a[i] = B + i \times w

where B is the base address and w is the size of one element. With B=2000B = 2000 and 4-byte ints, a[3] sits at 2000+3×4=20122000 + 3 \times 4 = 2012. 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 n−1n - 1.

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

B+(i×C+j)×wB + (i \times C + j) \times w

because i full rows of C elements come first, then j more elements. With B=1000B = 1000, C=4C = 4 and w=4w = 4, m[2][1] is at 1000+(2×4+1)×4=10361000 + (2 \times 4 + 1) \times 4 = 1036. 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>.

  1. strlen(s) counts the characters before '\0'.
  2. strcpy(d, s) copies s, with its '\0', into d.
  3. strcat(d, s) appends s to the end of d; with char u[10] = "ab", strcat(u, "cd") gave "abcd" of length 4.
  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.

  1. const int *p reads "p is a pointer to a const int": *p = 5 is an error, but p = &z is allowed.
  2. int *const p reads "p is a const pointer to an int": p = 0 is an error, but *p = 4 is allowed.
  3. const int *const p fixes 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 4×8=324 \times 8 = 32. 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.

  1. They ask you to differentiate an array from a pointer, or char s[] from char *s, with examples.
  2. They ask you to explain pointer arithmetic and the address formula for 1-D and 2-D arrays, with a numerical.
  3. They ask you to write string functions such as length, copy, reverse or palindrome check without using <string.h>.
  4. They ask you to show call by reference with pointers, or to explain const pointers and function pointers.

Practice questions (our own, not previous-year questions).

  1. Write a C function that reverses a string in place using two pointers, and trace it on "GATE". (10 marks)
  2. An array int a[10][20] is stored from address 5000 with 4-byte integers. Find the address of a[6][15] in row-major and in column-major order. (5 marks)
  3. "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, while sizeof(p) gives the pointer size.
  • Show the second exception: &a is a pointer to the whole array, so &a + 1 moves past all the elements.
  • Show that p = a is legal but a = p is 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 B+i×wB + i \times w, and indices run from 0 to n−1n - 1 with no bounds check.
  • A 2-D array is row-major, so a[i][j] is at B+(i×C+j)×wB + (i \times C + j) \times w.
  • A string ends with '\0', so sizeof("GATE") is 5 and strlen("GATE") is 4.
  • char s[] is a modifiable copy, while modifying the literal behind char *p is undefined.
  • strcmp returns 0 for equal strings, and string functions never check the destination size.
  • p + k moves k elements, and the difference of two pointers counts elements.
  • *p++ moves the pointer, (*p)++ changes the value and returns the old one, and ++*p returns 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 &x lets a function change x, which is how C simulates call by reference.
  • Read const declarations right to left: const int *p fixes the value and int *const p fixes the pointer.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. `int a[5] = {10, 20, 30};` What are `a[3]` and `a[4]`?

  2. `int a[50]` starts at address 2000 with 4-byte ints. The address of `a[12]` is:

  3. `void f(int a[]) { printf("%zu", sizeof(a) / sizeof(a[0])); }` is called with an array of 5 ints on 64-bit gcc. It prints:

  4. `int m[3][4]` is stored row-major from address 1000 with 4-byte ints. The address of `m[2][1]` is:

  5. `char s[] = "GATE";` What are `sizeof(s)` and `strlen(s)`?

  6. After `char *t = "GATE";`, the statement `t[0] = 'D';` is:

  7. For equal strings a and b, `if (strcmp(a, b)) printf("X"); else printf("Y");` prints:

  8. `int a[5]; int *p = &a[1], *q = &a[4];` With 4-byte ints, `q - p` is:

  9. `int a[] = {10, 20, 30}; int *p = a; int v1 = *p++; int v2 = (*p)++; int v3 = ++*p;` Then v1, v2, v3 and a[1] are:

  10. `int a[5];` What is `(int *)(&a + 1) - a`?

  11. For `int a[] = {10, 20, 30};`, which expression is NOT equal to 30?

  12. To let `swap` exchange the caller's x and y, the correct call is:

  13. `char *c[] = {"GATE", "EXAM", "QUIZ"}; char **cp = c;` What does `printf("%c", *(*(cp + 2) + 1));` print?

  14. Which declares a pointer to a function taking two ints and returning int?

  15. Given `int z = 3; int *const p = &z;`, which statement is an error?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is the difference between char s[] and char *p for a string?

char s[] makes a modifiable copy of the text, while char *p points to a string literal, and changing a literal is undefined behaviour.

Why does sizeof give a different answer inside a function?

An array parameter is really a pointer, so sizeof gives the pointer size, such as 8 bytes, not the size of the whole array.

What is the difference between *p++ and (*p)++?

*p++ reads the value and then moves the pointer to the next element. (*p)++ increments the value the pointer points to.

What is the difference between const int *p and int *const p?

With const int *p the value cannot be changed through p, but p can move. With int *const p the pointer is fixed, but the value can change.

More in this module: Programming in C

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Problem Solving through Programming in C (IIT Kharagpur, 106105171): arrays, strings and pointers