Open In App

Practice questions on Strings

String is an important topic from GATE exam point of view. We will discuss key points on strings as well different types of questions based on that. There are two ways to store strings as character array (char p[20]) or a pointer pointing to a string (char* s = “string”), both of which can be accessed as arrays. Assuming p as character array and s as pointer pointing to a string, following are the key points:

printf(“%c”, s[0]);
printf(“%c”, p[1]);
printf(“%s”, s);
printf(“%s”, p);

Let us discuss some problems based on the concepts discussed: 



Que – 1. What does the following fragment of C-program print?

char c[] = "GEEK2018";
char *p =c;
printf("%c,%c", *p,*(p+p[3]-p[1]));

Solution: As given in the question, p points to character array c[] which can be represented as: 



 

As p is a pointer of type character, *p will print ‘G’ Using pointer arithmetic, *(p+p[3]-p[1]) = *(p+75-69) (Using ascii values of K and E) = *(p+6) = 1(as we know p is holding the address of base string means 0th position string, let assume the address of string starts with 2000 so p+6 means the address of p(we are adding 6 in 2000 that means 2006, and in 2006 the “1”is stored that is why answer is 1). Therefore, the output will be G, 1. 

Que – 2. Which of the following C code snippet is not valid? 

Solution: Option (A) is valid as p is a pointer pointing to character ‘s’ of “string1”. Using ++p, p will point to character ‘t’ in “string1”. Therefore, *++p will print ‘t’. Option (B) is invalid as q being base address of character array, ++q(increasing base address) is invalid. Option (C) is valid as r is a pointer pointing to character ‘s’ of “string1”. Therefore,

r[1] = *(r+1) = ‘t’ and it will print ‘t’.

Que – 3. Consider the following C program segment: (GATE CS 2004)

char p[20];
char *s = "string";
int length = strlen(s);
int i;
for (i = 0; i < length; i++)
     p[i] = s[length — i];
printf("%s",p);

The output of the program is: 

Solution: In the given code, p[20] is declared as a character array and s is a pointer pointing to a string. The length will be initialized to 6. In the first iteration of for loop (i = 0),

  

p[i] = s[6-0] and s[6] is ‘\0’ Therefore, p[0] becomes ‘\0’. As discussed, ‘\0’ means end of string. Therefore, nothing is printed as first character of string is ‘\0’. 

Que – 4. What does the following fragment of C-program print?

char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;

Solution: As given in the question, p points to character array c[] which can be represented as: 

 

As p is a pointer of type character, using pointer arithmetic, p + p[3] – p[1] = p + 69 – 65 (Using Ascii values of A and E) = p + 4 Now, p + 4 will point to 2, the string starting from 2 till ‘\0’ will be printed which is 2011.

Article Tags :