Medium ●●

🔤 Strings & Characters

Why it matters: String loops with pointers, the null terminator and unsigned size_t pitfalls appear regularly as short output questions.

Subtopics

Each subtopic has its own page: idea, why, how, example, play, check. Mark each one understood when it clicks. 0 of 3 done.

Formulas

Storage for a string of n characters
n + 1 bytes (terminator)
sizeof vs strlen
sizeof("abc") = 4, strlen("abc") = 3
ASCII anchors
'0' = 48, 'A' = 65, 'a' = 97, so 'a' − 'A' = 32
Digit to value
c − '0'
strlen(a) − strlen(b)
unsigned: wraps modulo 2^64 when negative

What GATE asks from this

Question types seen repeatedly in past papers. More stars means more frequent.

★★★
What does this string loop print?
Simulate pointer s and t over the array; remember whether the terminator was copied.
★★★
Return value of a pointer-difference string function
b − a after advancing b to the terminator gives strlen(a).
★★★
Unsigned arithmetic with strlen
Compare lengths directly instead of subtracting.

Ratings are approximate, based on recurring patterns in past GATE CSE papers.

Previous year questions

3 real questions from the official GATE CSE papers (2017 to 2025), newest first, each with the official answer key and a worked solution. Questions are the property of the GATE organising institutes; this copy is for your personal study.

3 questions · 0 correct of 0 attempted · marks 0 / 4

Year:
GATE 2025 CS2 · Q19MCQ1 mark
Consider the following C program:
#include <stdio.h>
void stringcopy(char *, char *);
int main(){
  char a[30] = "@#Hello World!";
  stringcopy(a, a + 2);
  printf("%s\n", a);
  return 0;
}
void stringcopy(char *s, char *t) {
  while(*t)
    *s++ = *t++;
}
Which ONE of the following will be the output of the program?
GATE 2024 CS2 · Q33MSQ1 mark
Consider the following C function definition.
int fX(char *a){
  char *b = a;
  while(*b)
    b++;
  return b - a;
}
Which of the following statements is/are TRUE?

One or more options may be correct. Select all that apply, then submit.

GATE 2017 Set 1 · Q53NAT2 marks
Consider the following C program.
#include <stdio.h>
#include <string.h>

void printlength(char *s, char *t) {
  unsigned int c = 0;
  int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
  printf("%d\n", len);
}

void main() {
  char *x = "abc";
  char *y = "defgh";
  printlength(x,y);
}
Recall that strlen is defined in string.h as returning a value of type size_t, which is an unsigned int. The output of the program is ______.

Common traps

Forgetting the +1 for the null terminator.
Modifying a string literal is undefined.
if (strcmp(a,b)) is true when the strings are different.
sizeof on a char * gives 8, not the string length.