-4

Here's a part of my program.

I understand how s1 works but i am confused with s2

char* s1="string";
char s2[7]="string";
printf(  "\n &s2 is  :%p",&s2);
printf("\n\n  s2 is  :%p",s2);
printf(  "\n *s2 is  :%c",*s2);

Output

&s2 is  :0018FF48 //i.e. s2 is contained in memory address 0013FF48    
 s2 is  :0018FF48 //i.e  s2 points to  0013FF48
*s2 is  :s        //i.e  value contained in 0013FF48 is s

This is summarized below and I can't figure out it's meaning:

  • s2 is contained in 0018FF48, s2 contains 0018FF48 and address no 0018FF48 contains 's'

what role actually s2 is playing?

Sudip Bhattarai
  • 1,082
  • 9
  • 23
  • `"%zu"` is the format for `size_t`. And this is either pre-C++11 or C. Please decide. – Deduplicator Jan 23 '15 at 21:41
  • https://stackoverflow.com/questions/2245664/string-literals-in-c https://stackoverflow.com/questions/2589949/c-string-literals-where-do-they-go https://stackoverflow.com/questions/25928543/identical-string-literals-are-considered-equal – Deduplicator Jan 23 '15 at 21:44
  • I use code blocks 13.12 and writing %zu doesn't work. – Sudip Bhattarai Jan 24 '15 at 08:29
  • What compiler and library, on what platform? The IDE isn't really relevant... – Deduplicator Jan 24 '15 at 08:36
  • Compiler setting shows that default is : GNU GCC compiler. And I have not found my answer to the question : when is it preferred to use 1st declaration instead of 2nd one in the link that was provided. Is there no way to unduplicate it? – Sudip Bhattarai Jan 24 '15 at 08:45
  • You haven't demonstrated hat the question isn't a dupe yet. And, I concurr it's a dupe. In general, the method is clarifying your question so it's obviously not a dupe (just stating you don't think so is a useless waste of time). That will put it into the queue for consideration, which is handled quite fast. – Deduplicator Jan 24 '15 at 08:56

1 Answers1

1

char s2[7]="string"; is a array of 7 chars and a initial value.
char *s1="string"; is string constant somewhere in the program binary, not changeable during runtime, and a pointer to access it. You must not free it.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • And the second is also ill-formed since C++11. And might share space with other string-literals (and constant compound-literals since C99). – Deduplicator Jan 23 '15 at 21:46