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?

Gokul
  • 73
  • 8
  • Is that a local or global variable? – Retired Ninja Feb 03 '18 at 06: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' };` – David C. Rankin Feb 03 '18 at 06: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. – Jonathan Leffler Feb 03 '18 at 06:38
  • 2
    Ahh -- funny what the mind will overlook when it is expecting something logical... – David C. Rankin Feb 03 '18 at 06:40
  • In this case, the dimension IS specified if `s` is an array of char - `"Hello"` is used to initialise `s`, and the dimension is `sizeof("Hello"`) i.e. `6`. For `s` being an array of `int`, the code won't compile. – Peter Feb 03 '18 at 06:40
  • 1
    error C2440: 'initializing': cannot convert from 'const char [6]' to 'int []' – YePhIcK Feb 03 '18 at 07:00

1 Answers1

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'};
H.S.
  • 11,654
  • 2
  • 15
  • 32