简体   繁体   中英

How is space allocated char* arrays?

For example, in

#define NUM_THREADS 8
char *messages[NUM_THREADS];
messages[0] = "English: Hello World!";
messages[1] = "French: Bonjour, le monde!";
messages[2] = "Spanish: Hola al mundo";
messages[3] = "Klingon: Nuq neH!";
messages[4] = "German: Guten Tag, Welt!"; 
messages[5] = "Russian: Zdravstvytye, mir!";
messages[6] = "Japan: Sekai e konnichiwa!";
messages[7] = "Latin: Orbis, te saluto!";

During compile time, does the compiler calculate the maximum length of all those strings and then reserve space = NUM_THREADS * ( max_len + 1 ). Added 1 for the null byte at the end of strings. Or is different amount of space allocated for each of those strings depending on their length rounded up to the nearest word?

However, this can't always be possible since the initialization need not necessarily happen at compile time. I'm assuming a pointer to the data section where the strings will be stored is held with messages[i].

The memory used by those strings is exactly as long as the string length plus one (the terminating null character). The array you defined has 4*NUM_THREADS bytes (assuming your vanilla variety of 32-bit C compiler) since it only holds pointers, not copies of the entire strings.

There's no rounding, no guessing, no fuzzing of data. This is C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM