编译器如何将内存分配给未指定维度的数组?

时间:2018-02-03 06:26:23

标签: c dynamic-memory-allocation

实施例。 char s[]="Hello";

据我所知,字符串常量存储在堆栈内存中,而未指定维度的数组存储在堆内存中。如何将记忆分配给上述陈述?

1 个答案:

答案 0 :(得分: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'};