When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then the string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.
Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.
Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.
A data segment is a portion of the virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer. Note that, the data segment is not read-only, since the values of the variables can be altered at run time.
I'm wondering what's the difference between char s[] = "hello"
and char *s = "hello"
.
After reading this and this, I'm still not very clear on this question.
As I know, there are five data segments in memory, Text, BSS, Data, Stack and Heap.
From my understanding,
in case of char s[] = "hello"
:
"hello"
is in Text.s
is in Data if it is a global variable or in Stack if it is a local variable.
We also have a copy of "hello"
where the s
is stored, so we can modify the value of this string via s
.
in case of char *s = "hello"
:
"hello"
is in Text.s
is in Data if it is a global variable or in Stack if it is a local variable.s
just points to "hello"
in Text and we don't have a copy of it, therefore modifying the value of string via this pointer should cause "Segmentation Fault".Am I right?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With