1

I am working with C and in the snippet below I think the assignment to c is OK. The assignments to cArr[] run OK but it doesn't seem right to me. It seems I should have to use something like:

char cArr[3][80];

Or are these strings being placed on the heap?

int main(int argc, char** argv)
{
    char* c = "abcd";

    char* cArr[3];

    cArr[0] = "A string of of characters.";
    cArr[1] = "Another inane comment.";
}

2 Answers 2

4

First case:

char* c = "abcd";

c is of type char *. The base address of the string "abcd" is stored into that. Correct.

Second Case:

char* cArr[3];

cArr is an array of three char *s.

cArr[0] = "A string of of characters.";
cArr[1] = "Another inane comment.";

is also fine and legal. You're storing the base address of the string literals into a variable of type char * (here, cArr[n]). There is no issue with that.

Or are these strings being placed on the heap?

Not really. Standards only specify that the string literals should have static storage duration. Usually string literals are placed in read-only memory locations so you may not be able to modify the strings pointed by cArr[n]. So, basically it's implementation dependent where the string literals are stored. As mentioned in this previous answer, strings are stored in the .rodata section of your binary.

Sign up to request clarification or add additional context in comments.

1 Comment

@MattMcNabb sir, I have added a little description to my answer. Can you please review it?
1
char* c = "abcd";

Makes a string literal and c points to the address of the first element.

char* cArr[3];

Creates an array of three char* pointers and the below statements can be used to make them point to string literals, which are static:

cArr[0] = "A string of of characters.";
cArr[1] = "Another inane comment.";

The above statements are perfectly valid. The string literals are allocated in the rodata memory segment and thus, they are read-only and are not writable.

6 Comments

They aren't on the heap. They're static.
Dosen't static imply that they are on the heap? Dosen't the same apply for global variables,i.e, they are allocated on the heap?
No. "heap" isn't an official term in C but common usage is the area in which allocations made by malloc and family are stored. Historically it's called "heap" because the data structure named "heap" was used to track all those allocations. Also see Where are static variables stored in C?
I did a poor job on posing my question. Suppose cArr[] variable are dynamically determined as in: cArr[2] = strtok(NULL, delim); vj
@Vince it doesn't matter as long as you don't need to copy whole string. Usually functions returning char * can have their result stored under pointer (as it is with your cArr[i]).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.