1

For example, the following code returns an error and a warning when compiled and an int when changed to %d

Warning: format %s expects argument of type char *, but argument 2 has type int

void stringd() {
    char *s = "Hello";
    printf("derefernced s is %s", *s);
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
mn0o7
  • 65
  • 8

2 Answers2

7

*s is an expression of type char since it's the dereference operator applied to a pointer-to-char1. As a result, it gets promoted to an int when passed to printf; in order to print a null-terminated string, you need to pass the pointer to the first character (i.e. just s).

1 even though s is not a const pointer, you should not try to modify the characters it points to as they may be placed in read-only memory where string literals are stored on some architectures/environments; see this discussion for more details.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
3

The variable s is a pointer to the first out of a series of characters which are consecutive in memory (colloquially referred to as a "string", though it's not quite the same). It's a pointer to a character, thus char *.

Dereferencing s (by doing *s) gives you the first of those characters, h, whose type is now just char. One layer of indirection was stripped away.

Thus, the issue is that you're trying to pass a character (char), where a string (char *) was expected. char * was expected because you used the %s type character in your format string to printf. Instead, you should use %c, which expects single, simple char.

The mistake here is actually quite grave. If you were allowed to pass this 'h' where a char * was expected, you would end up with the ASCII code of 'h' (0x68) being passed where a pointer was expected. printf would be none-the-wiser, and would try to dereference that value, treating 0x68 like a pointer to the beginning of a string. Of course, that's probably not a valid memory location in your program, so that should seg-fault pretty reliability, if it were allowed to happen.

Alexander
  • 59,041
  • 12
  • 98
  • 151