1

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?

6
  • Is that a local or global variable? Commented Feb 3, 2018 at 6:36
  • 4
    s[] is an array initialized with the literal "Hello". The compiler knows the size of "Hello" to begin with. There is nothing dynamic about the initialization or storage. That is a valid initializer that initializes s as { 'H', 'e', 'l', 'l', 'o', '\0' }; Commented Feb 3, 2018 at 6:36
  • 4
    The code shown won't allocate any memory; a string literal is not an appropriate initializer for an array of int (but it would be fine for an array of char). I'm also puzzled about your claim that string constants are stored in stack memory — that isn't where I'd expect to find them. Commented Feb 3, 2018 at 6:38
  • 2
    Ahh -- funny what the mind will overlook when it is expecting something logical... Commented Feb 3, 2018 at 6:40
  • 1
    error C2440: 'initializing': cannot convert from 'const char [6]' to 'int []' Commented Feb 3, 2018 at 7:00

1 Answer 1

3

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'};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.