Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the compound/string literals get stored in the memory?

I read that ;

A compound literal is a C99 feature that can be used to create an array with no name. Consider the example:

int *p = (int []){3, 0, 3, 4, 1};

p points to the first element of a five- element array containing 3, 0, 3, 4, and 1.

Actually I want to know, Is this array will stored in memory or not as it doesn't have a name?
In other words in case of

char* str = "hello"

Where the string "hello" will stored in memory?

like image 281
haccks Avatar asked Jul 26 '13 20:07

haccks


People also ask

Where are string literals stored on the stack?

The stack will store the value of the int literal and references of String and Demo objects. The value of any object will be stored in the heap, and all the String literals go in the pool inside the heap: The variables created on the stack are deallocated as soon as the thread completes execution.

How strings are stored in memory in C?

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 string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

How does compiler process string literal?

The compiler scans the source code file, looks for, and stores all occurrences of string literals. It can use a mechanism such as a lookup table to do this. It then runs through the list and assigns the same address to all identical string literals.

What are compound literals in C?

In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object that only lives until the end of its full-expression.


1 Answers

Using pointer arithmetic. So

p[0], p[1], ...

or

*p, *(p + 1), ...

Here's the thing. In C, you have nice literals for primitive types like int and char, and even string literals. So, we can easily say things like

int length(char *s);
int len = length("Hello, World!");

In C99, the concept of compound literals was added to handle "array literal" and "struct literal". Therefore, we can now say things like:

int sum(int a[], int n);
int total = sum((int []){ 17, 42 }, 2);

This is using a compound literal to represent an "array literal".

Actually I want to know, Is this array will stored in memory or not as it doesn't have a name?

Yes, in memory.

I think your confusion stems from this. p has a name. (int []){3, 0, 3, 4, 1} does not. It just so happens that p's value is the address of (int []){3, 0, 3, 4, 1}. Of course (int []){3, 0, 3, 4, 1} is in memory; it will be in the data segment for your executable. You just don't have any name with which to refer to it.

like image 116
jason Avatar answered Sep 22 '22 17:09

jason