-4

What is the difference between the following notations in string definition from a program address space point of view?

char str[20] = "Just to Ask";

char *str = "Just to Ask";
Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
  • `"Just to ask"` is a (read-only) array of 12 characters. In the first line, you are copying it, char by char, to a different array; in the second line you are creating a pointer to the first element. To answer your question: if you need a changeable array use the first notation; if you need a pointer to a (read-only) string use the second. – pmg Apr 19 '14 at 08:38

1 Answers1

0
char str[20] = "Just to Ask";

The above statement defines an array str of 20 characters and initializes the array with the string literal "Just to Ask". The above statement is equivalent to

char str[20] = {'J', 'u', 's', 't', ' ', 't', 'o', ' ', 'A', 's', 'k', '\0'};

The array initializer list has only 12 elements. The rest 8 elements of the array str are initialized to 0. If the array has automatic storage allocation, then it is allocated on the stack. If it has static storage allocation, then it is allocated in the data section of the program memory space.

The below statement

char *str = "Just to Ask";

defines str not an array but a pointer which points to the string literal "Just to Ask". The string literal is read-only and attempting to modify it is undefined behaviour. Therefore, the two statements stated in your questions are totally different and the second statement better be written as

const char *str = "Just to Ask";  // string literal is read-only
ajay
  • 9,402
  • 8
  • 44
  • 71
  • Thanks Ajay for you answer .. One more thing.. the statement char *str = "Just to Ask" will be in code segment ??? and thats why is in read only ??? While the char str[20] = "Just to Ask"; can be in data segment or stack on the basis of its declaration?? – user3551208 Apr 19 '14 at 10:43
  • @user3551208 The string literal `"Just to Ask"` will be stored in a read-only memory. Generally it is code segment but it's not guaranteed and should not matter to the behaviour of the program. Please understand that `str` in `char *str = "Just to Ask"` is a character pointer where as `str` in `char str[] = "Just to Ask"` is an array. – ajay Apr 19 '14 at 10:49
  • If the statement `char str[] = "Just to Ask";` is inside a function body, then the array is allocated on the stack. If it outside of any function, i.e., is global, then it allocated in the data segment. Same case holds for the statement `char *str = "Just to Ask";` – ajay Apr 19 '14 at 10:51
  • Hi ajay,Definetly your answer helped me.Is there any procedure to do explicitly to accepting your answer in future like sbscription and all or i will continue to get your answer without doing anything. – user3551208 Apr 21 '14 at 08:58