bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / letusc / luc072.c

luc072.c (1966B)


      1 /* How many bytes in memory would be occupied by the following array of pointers to strings? How many bytes would be required to store the same strings in a two-dimensional character array?
      2 */
      3 
      4 /* Let Us C, Chap- 16 (Handling Multiple Strings), Qn No.: A(a) */
      5 
      6 /* This file is auto-generated by a bot. */
      7 /* This code is not compiled; it is for reference only. */
      8 
      9 
     10 #include <stdio.h>
     11 #include <string.h>
     12 #include <stdlib.h>
     13 #include <ctype.h>
     14 
     15 int main()
     16 {
     17     /* Question Analysis:
     18        char *mess[] = {"Hammer and tongs", "Tooth and nail", "Spit and polish", "You and C"};
     19        
     20        1. Array of Pointers (*mess[]):
     21           - It stores 4 pointers. 
     22           - Size of a pointer is typically 4 bytes (32-bit) or 8 bytes (64-bit).
     23           - Total = 4 * sizeof(char*)
     24           - Plus the strings themselves are stored elsewhere in memory.
     25        
     26        2. Two-Dimensional Array (mess[][]):
     27           - Must accommodate the longest string ("Hammer and tongs" = 16 chars + null = 17).
     28           - Width would be 17 (or more).
     29           - Size = 4 rows * 17 cols * 1 byte.
     30     */
     31 
     32     char *mess_ptr[] = {
     33         "Hammer and tongs", 
     34         "Tooth and nail", 
     35         "Spit and polish", 
     36         "You and C"
     37     };
     38 
     39     // Longest string length + 1 for null terminator
     40     // "Hammer and tongs" is 16 chars long.
     41     char mess_2d[4][17] = {
     42         "Hammer and tongs", 
     43         "Tooth and nail", 
     44         "Spit and polish", 
     45         "You and C"
     46     };
     47 
     48     printf("--- Memory Occupation Analysis ---\n\n");
     49 
     50     printf("1. Array of Pointers (char *mess[]):\n");
     51     printf("   Size of array object itself (4 pointers): %zu bytes\n", sizeof(mess_ptr));
     52     printf("   (Note: The string literals are stored in read-only memory separately)\n\n");
     53 
     54     printf("2. Two-Dimensional Array (char mess[4][17]):\n");
     55     printf("   Size of 2D array: %zu bytes\n", sizeof(mess_2d));
     56     printf("   (Calculation: 4 rows * 17 columns * 1 byte)\n");
     57 
     58     return 0;
     59 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror