1

Inspired by this question.

Code:

#include <stdio.h>

int main()
{
   char arr[] = "Hello";
   char *ptr = arr + 5;
   printf("%s\n",ptr);
}

In the above code, I have accessed null-terminated character.

So, What actually happens when accessing null terminated character in literal string? Is it Undefined behaviour?

msc
  • 32,079
  • 22
  • 110
  • 197
  • 2
    By "accessing" you mean reading? Why would the null character be any different to any other character in the string? If you tried to write, went *beyond* the bounds of the string, then the effect is undefined. – cdarke Jun 27 '18 at 05:50

3 Answers3

5

Essentially, you're passing an empty string as the argument, so it should be treated as such.

For %s conversion specifier, with printf() family

[...]Characters from the array are written up to (but not including) the terminating null character.[...]

In your case, the null terminator happens to appear at the first element in the array, that's it.

Just for clarification, accessing a null-terminator is OK, accessing a NULL pointer is not OK, and they both are different things!!

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
4

You are basically still accessing a null-terminated string.
It is just zero characters long, i.e. it does not contain anything to print.

Your code is basically the same as

 printf("");

Compare this, not duplicate but similar question:

Effect of "+1" after the format string parameter to printf()

Yunnosch
  • 24,749
  • 9
  • 40
  • 51
1

Nothing particular. A pointer to the null character is interpreted as a zero-length string by functions that expect a string.

Matteo Italia
  • 119,648
  • 17
  • 200
  • 293