0

In a quiz today, we got this as our question2.

After seeing this, most of us believe that we will fail quite badly.

#include <stdio.h>

int main ( ) {
  char str[] = "StanfordIsGreat";

  char *ptr = str;

  printf("%s", ptr);
  printf("%s", ptr + 8);
  printf("%s", ptr + 'l' - 'b');
  printf("%s", ptr + 'k' - ptr[3]);
}

So can anyone guide me answer this question?

what i applied for 1st printf was that the actual string will be printed StanfordIsGreat

for 2nd printf, i think the pointer will shift 8 indexes to the right generating IsGreat

for 3rd printf, ptr + 'l' gave me StanfordIsGreatl, i didn't understand what - 'b' meant

for 4rth printf ptr + 'k' was same as above and ptr[3] stands for 'a' so i wrote StnfordisGretk

i am really confused about 3rd and 4rth, can someone guide me, so i can learn and not make mistakes like this for future quizes.

1 Answer 1

3
char str[] = "StanfordIsGreat";

Character array(string) which contains content StanfordIsGreat.

char *ptr = str;

Character pointer that points to the 1st letter of the string (S).

printf("%s", ptr);

Direct printing the string pointed from the pointer index till the end of the string hence
Output: StanfordIsGreat

printf("%s", ptr + 8);

Pointer is shifted 8 index, pointing to 'I' in StanfordIsGreat therefore printing from 'I' to end of string
Output: IsGreat

printf("%s", ptr + 'l' - 'b');

Easy if you know the ASCII values for 'l' and 'b', here you must subtract the ASCII values of 'l' and 'b' giving you 10, giving you equation ptr+10 which equals pointer pointing to 'G'.
Output: Great

printf("%s", ptr + 'k' - ptr[3]);

Same as above but tricking you with ptr with index, ptr[3] points to 'n' therefore now you must subtract 'k' and 'n', giving you a -ve value, an unexpected behaviour will rise due to ptr-value.
Output: Not Clear Since we don't have a memory pool to overview

Edited: thanks mch for clearing an error :)

Hope you understand :)

Sign up to request clarification or add additional context in comments.

2 Comments

Given that C does not mandate ASCII, the third and fourth printf()s could easily index out of bounds.
ptr[3] is 'n', not 'a', so the resulting pointer in the last printf will point before the array and so it will invoke undefined behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.