Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...