In C, consider the following "inline" string arrays:
char *string1 = "I'm a literal!";
char *string2 = malloc((strlen(string1) + 1) * sizeof(char));
//Do some string copying
...
char string3[] = {'a','b','c','\0'};
char *stringArray[] = {string1, string2, string3};
Would stringArray
simply contain a copy of each of three pointers?
Would the array be allocated on the stack?
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.
Rust arrays are value types: they are allocated on the stack like other values and an array object is a sequence of values, not a pointer to those values (as in C). So from our examples above, let a = [1_i32, 2, 3, 4]; will allocate 16 bytes on the stack and executing let b = a; will copy 16 bytes.
A string constant in C is represented by a sequence of characters within double quotes. Standard C character escape sequences like \n (newline), \r (carriage return), \a (bell), \0x17 (character with hexadecimal code 0x17), \\ (backslash), and \" (double quote) can all be used inside string constants.
The stringArray
is allocated on the stack, each of its element is a pointer to a char
. To be more specific :
string1
pointer is on the stack, its value is the address of the first character of a read-only string in the data segmentstring2
pointer is on the stack, its value is the address of a memory block allocated on the heapstring3
is an array which occupies 4 * sizeof(char)
bytes on the stackstringArray
is an array which occupies 3 * sizeof(char *)
bytes on the stack.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