0
char my_name[] = "Red";

char *my_name = "Red";

Does the latter get stored in stack as well if called inside a function?

shortint
  • 17
  • 1
  • 4
  • 8
    These two statements do different things and neither is "preferred". It depends on the larger context to determine which is more appropriate. The first statement creates an array that contains a string that can be modified. The second one is a pointer to a string literal and thus the string cannot be modified. – kaylum Mar 01 '20 at 02:44
  • 1
    The second one should really be `const char *my_name = "Red";` to reflect that string constants cannot be modified in many platforms (as @kaylum suggests). But there's not an obvious "better" to either one. – Steve Friedl Mar 01 '20 at 02:46
  • Okay, understood. Thank you! – shortint Mar 01 '20 at 02:51
  • So where does *my_name get stored? – shortint Mar 01 '20 at 02:53
  • Where variables are stored depends on whether they are static or automatic. The former ones go in the `bss`, `data` or `rodata` section, the latter ones on the stack. But the characters, which the pointer `my_name` points to, are stored in the read-only `rodata` section, most commonly. However, you can change the value of pointer `my_name`. – the busybee Mar 01 '20 at 15:40

0 Answers0