0

The sizeof(test) returns 24. It is an array of 3 char* pointers which are 8 bytes each on my machine. My question is does C properly allocate space for the characters as well? I guess it does because this works but I want to make sure I am doing it correctly.

char* test[] = {"QW", "BT", "GH"};
int size = sizeof(test) / sizeof(char*);

4 Answers 4

6

Yes, it does. The characters may be in a read-only portion of the memory though.

3

Yes, the compiler will allocate space (generally in the read-only static data section) for the string literals.

2

Yes. The value is located in memory at the address pointed by the *char pointer used in the array. So yes, it is stored in the memory.

0

My rewording of 6.4.5/5 in the Standard

... string literals are implemented as arrays of static storage duration with 'char' type ...

So, the objects are allocated as any other static variable

static int arr[100] = {0};
if (strcmp(foo, "bar")) exit(0);
int *ptr = malloc(100 * sizeof *ptr);

The array arr and the string literal "bar" are allocated in the same way; different than the way ptr is allocated.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.