I read that while using character pointer declaration first the string literal is getting stored in static storage and then pointer to it is returned. but is same happening while using literals in char array?
here I know "instatic" gets stored in static storage because it is char literals and then test receives the address of the first character.
char *test = "instatic";
but in this declaration it also uses char literals and are they first located in static storage and then they get copied to stack?
char test[] = "instatic?";
Formally, a string literal is text in source code that is a sequence of characters enclosed in
"marks, optionally with an encoding prefix ofu8,u,U, orL, per C 2018 6.4.5 1.In the abstract model of computing used in the C standard, any string literal, regardless of how it is used, results in the creation of an array of static storage duration that is initialized with the contents of the string, including a terminating null character, per 6.4.5 6.
That static array might or might not appear in the actual program generated by a compiler, depending on how it is used and how the compiler optimizes the program. In other words, the abstract program described by the C standard always contains a static array for a string literal, but the actual program produced by a C compiler, with optimization, might produce the same behavior as the abstract program without actually using a separate static array for the string literal, per 5.1.2.3 6.
In the case of
char *test = "instatic";, the compiler generally must create the static array so thattestcan point to it. (This might not occur iftestis not used or perhaps if only individual characters from the array are used, as the compiler could then perform some optimizations that make the full array unnecessary.)In the case of
char test[] = "instatic?";appearing at file scope, a compiler typically produces object code that defines the arraytestwith the contents of the string, so a separate static array for the string is not needed. This is a form of optimization: In the abstract model of computing, an array for the string is created, separate memory is allocated fortest, and the contents of the string are copied into the array. However, in practice, the contents of the string are made to be the initial contents of memory for the array as part of the program loading process.In the case of
char test[] = "instatic?";appearing at block scope (inside a function), the compiler generally needs to create that separate static array for the string, because, each time execution of the block begins, the compiler has to allocate memory for thetestarray and then initialize it. This cannot be made part of the program loading process because it has to happen multiple times during program execution. Again, optimization may be able to reduce this, depending on circumstances.