-3

What's the difference between:

char *s1 = "dog";
char s2[] = "dog";
printf("%s", s1);
printf("%s", s2);

The first one doesn't print anything and the second prints dog as expected.

It seems to me they should be equivalent, as the right-hand side of char *s1 = "dog"; initializes a char array under the hood, and assigns the address of its first character to s1. s2 is an array and thus contains the address to the first charcter in the string. So doesn't both s1 and s2 contain pointers to a the first character in a string "dog"? What am i missing? thanks!

  • 2
    The output I got was `dogdog` – qrsngky Aug 09 '22 at 09:00
  • 1
    Can you do `"%s\n"` so any buffer is flushed to the output? – Joop Eggen Aug 09 '22 at 09:03
  • 5
    Aladin, "The first one doesn't print anything and the second prints dog as expected." --> How do you know it wasn't the other way around? Try using different text. – chux - Reinstate Monica Aug 09 '22 at 09:03
  • 1
    @chux-ReinstateMonica I already wanted to mention just that: cat/dog. I think it is an unflushed buffer. – Joop Eggen Aug 09 '22 at 09:05
  • I tried them also separately... Though I am using an online compiler I guess this is the problem... thanks! –  Aug 09 '22 at 09:07
  • 1
    Although they might print same thing, these two expressions aren't equivelent. Here is an example question: [String literals: pointer vs. char array](https://stackoverflow.com/questions/12795850/string-literals-pointer-vs-char-array) – zibidigonzales Aug 09 '22 at 09:57

1 Answers1

1

Please post a minimum, complete verifiable example and not a code snippet. That is a small runnable program exhibiting your problem. In short please do as much work as you can to make it easier to understand and explore your problem.

See here: https://stackoverflow.com/help/minimal-reproducible-example

When I execute the program below the output is dogdog as expected. You haven't included any output formatting. In C printf() doesn't add a newline. For that change the first print to printf("%s\n",s1).

\n means 'newline` and will produce:

dog
dog

.

#include <stdio.h>

int main(void) {
 
    char *s1 = "dog";
    char s2[] = "dog";
    printf("%s", s1);
    printf("%s", s2);
     
    return 0;
}
Persixty
  • 8,165
  • 2
  • 13
  • 35