Ex. char s[]="Hello";
As per my knowledge, string constants are stored in stack memory and array with unspecified dimension are stored in heap memory. How memory will be allocated to above statement?
Ex. char s[]="Hello";
As per my knowledge, string constants are stored in stack memory and array with unspecified dimension are stored in heap memory. How memory will be allocated to above statement?
First of all, the statement:
int s[]="Hello";
is incorrect. Compiler will report error on it because here you are trying to initialize int
array with string
.
The below part of the answer is based on assumption that there is a typo and correct statement is:
char s[]="Hello";
As per my knowledge, string constants are stored in stack memory and array with unspecified dimension are stored in heap memory.
I would say you need to change the source from where you get knowledge.
String constants (also called string literals) are not stored in stack memory. If not in the stack then where? Check this.
In the statement:
char s[]="Hello";
there will not be any memory allocation but this is char
array initialized with a string constant.
Whenever we write a string, enclosed in double quotes, C automatically creates an array of characters for us, containing that string, terminated by the \0
character.
If we omit the dimension, compiler computes it for us based on the size of the initializer (here it is 6, including the terminating \0
character).
So the given statement is equivalent to this:
char s[]={'H','e','l','l','o','\0'};
Can also be written as:
char s[6]={'H','e','l','l','o','\0'};