-4

I had to print the string but it is just showing errors ;/

This is my code:

#include <stdio.h>

int main(){
    char str[] = "Harry";
    char *ptr = str;
    while(*ptr != '\0'){
        printf('%c', *ptr);
        ptr++;
    }
    
    return 0;
}

I tried to print The String As Harry and its showing this:

Strings.c: In function 'main':
Strings.c:9:16: warning: multi-character character constant [-Wmultichar]
         printf('%c', *ptr);
In file included from Strings.c:1:0:
c:\mingw\include\stdio.h:454:38: note: expected 'const char *' but argument is of type 'int'
 _CRTIMP __cdecl __MINGW_NOTHROW  int printf (const char *, ...);
                                      ^~~~~~
Chris
  • 26,361
  • 5
  • 21
  • 42
  • Welcome to Stack Overflow. Who taught you to write a `printf` statement that way? – Beta Apr 29 '23 at 03:13
  • 3
    In C, string should be wrapped by double quote `"`, not `'`. – Paul Apr 29 '23 at 03:14
  • I'm getting from this that [you don't understand](https://stackoverflow.com/questions/7755202/multi-character-constant-warnings) what the compiler is complaining about when it says `warning: multi-character character constant [-Wmultichar] printf('%c', *ptr);` – Wyck Apr 29 '23 at 04:08
  • Also note you can print a string in one go with the `"%s"` format specifier instead of one character at a time in a loop: `printf("%s\n", ptr);`. Or `printf("%s\n", str);`, there's really no need for `ptr`. – yano Apr 29 '23 at 04:17

1 Answers1

5

printf() expects a format string as in "%c" but you passed in an (invalid) integer constant '%c'. I streamlined your code a bit too:

#include <stdio.h>

int main(void) {
    char str[] = "Harry";
    for(char *ptr = str; *ptr; ptr++)
        printf("%c", *ptr);
}

You could just do char *ptr = "Harry" in this case, but in general it means you no longer have a pointer to the original string.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38