Home > Software design >  what does a "storage class static" for an array do?
what does a "storage class static" for an array do?

Time:09-05

In The C Programming Language, Second Edition, 1988, Section A2.6, page 194, Kernighan and Ritchie write:

A string has type “array of characters” and storage class static…

and I do not understand the second information well, can you explain it to me?

CodePudding user response:

It means that the memory allocated the string will remain for as long as the program runs, similar to a global or static variable. This is different from automatic local variables, which are deallocated once the lexical scope ends.

CodePudding user response:

The text should say that a string literal has type “array of char” and storage class static.

A string literal is text in C source code starting and ending with ", such as "Hello, world." (There are some embellishments to that form, not discussed in this answer.) A compiler builds the contents of that string literal into your program so that it exists in memory for the entire execution of the program. This is what we mean by static storage duration: It is static (unchanging) throughout the program. In contrast, variables declared inside functions, particularly inside blocks, are given memory only during execution of the block they are in, and objects given memory by malloc have that memory only until free is called (or certain related routines).

Kernighan and Ritchie should not have used “string” in this sentence instead of “string literal.” In C terminology, a string is any sequence of characters terminated by a null character (and not containing any earlier null characters). You can have a string in any memory, whether it is static, thread, automatic, or dynamically allocated.

Also, technically, a string literal is the source code that starts with " and ends with ". The array that results from it is a different thing. However, people often use the term “string literal” loosely to refer to that array.

  • Related