3

Why this code does not work?

int main(){
  char *str ="abcde";
   scanf("%s",str);
  printf("%s",str);
}

but this works?

int main(){
  char str[] ="abcde";
   scanf("%s",str);
  printf("%s",str);
}`
bzlm
  • 9,626
  • 6
  • 65
  • 92
code4fun
  • 2,661
  • 9
  • 25
  • 39

3 Answers3

5

In the first code, you declare a pointer, which points to a string literal: "abcde".
This might be a constant, and you will not be able to change it.

The second code is declaring an array and filling it with ['a','b',c','d','e','\0'], and is not a constant - so you can change it.

amit
  • 175,853
  • 27
  • 231
  • 333
  • can the input for str[] case take more values than the size with which it initialized(6 in this case). – code4fun Feb 19 '12 at 00:38
  • @gaurav: I did not understand the question [in comment], can you clarify it? – amit Feb 19 '12 at 00:39
  • I think he's asking if the array is of size 6 can the input take more than 6 characters. Which the answer is yes and you must carefully check for that. – Timeout Feb 19 '12 at 00:41
  • yeah.i was asking that coz we are not specifying the size here..it seems it accepts few more characters unitl there is no more free continuous space – code4fun Feb 19 '12 at 00:48
  • @gaurav: You are guaranteed to have array of the size of the string [including the '\0']. Everything other then that - is undefined behavior - it might work and it might fail. – amit Feb 19 '12 at 00:52
4

Because char *str ="abcde"; is a pointer to string literal which is most likely stored in read-only memory.

char str[] ="abcde"; is an array initialized with "abcde".

You should also check out Difference between char* and char[]

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
  • 1
    String literals are not `const`. They just (may be) in read-only. – asaelr Feb 19 '12 at 00:48
  • *"An ordinary string literal has type "array of n const char" and static storage duration."* – LihO Feb 19 '12 at 00:59
  • 2
    That's C++ standard. We are talking about C. See http://stackoverflow.com/a/2245983/1055952 – asaelr Feb 19 '12 at 01:05
  • @asaelr: Nice one. I thought it's same in C. I have edited my answer, it should be OK now. – LihO Feb 19 '12 at 01:08
  • 1
    Note that "read-only memory" in this context probably doesn't mean hardware ROM; it's more likely just a segment of memory that's write-protected by the OS. (Though it could be actual ROM on an embedded system.) – Keith Thompson Feb 19 '12 at 01:22
1

When string value is directly assigned to a pointer, it’s stored in a read only block(generally in data segment) that is shared among functions

char *str  =  "GfG";

...

char str[] = "GfG";  /* Stored in stack segment like other auto
variables */  *(str+1) = 'n';   /* No problem: String is now GnG */

http://www.geeksforgeeks.org/archives/5328

perreal
  • 94,503
  • 21
  • 155
  • 181