Skip to content

luc072.c

Problem Statement

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?

Metadata

Property Detail
Author Amit Dutta amitdutta4255@gmail.com
Date 08 Feb 2026
License MIT License (See the LICENSE file for details)

Actions

Raw View on GitHub

💡 You can print or save this file by opening Raw and using your browser.

Source Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    /* Question Analysis:
       char *mess[] = {"Hammer and tongs", "Tooth and nail", "Spit and polish", "You and C"};

       1. Array of Pointers (*mess[]):
          - It stores 4 pointers. 
          - Size of a pointer is typically 4 bytes (32-bit) or 8 bytes (64-bit).
          - Total = 4 * sizeof(char*)
          - Plus the strings themselves are stored elsewhere in memory.

       2. Two-Dimensional Array (mess[][]):
          - Must accommodate the longest string ("Hammer and tongs" = 16 chars + null = 17).
          - Width would be 17 (or more).
          - Size = 4 rows * 17 cols * 1 byte.
    */

    char *mess_ptr[] = {
        "Hammer and tongs", 
        "Tooth and nail", 
        "Spit and polish", 
        "You and C"
    };

    // Longest string length + 1 for null terminator
    // "Hammer and tongs" is 16 chars long.
    char mess_2d[4][17] = {
        "Hammer and tongs", 
        "Tooth and nail", 
        "Spit and polish", 
        "You and C"
    };

    printf("--- Memory Occupation Analysis ---\n\n");

    printf("1. Array of Pointers (char *mess[]):\n");
    printf("   Size of array object itself (4 pointers): %zu bytes\n", sizeof(mess_ptr));
    printf("   (Note: The string literals are stored in read-only memory separately)\n\n");

    printf("2. Two-Dimensional Array (char mess[4][17]):\n");
    printf("   Size of 2D array: %zu bytes\n", sizeof(mess_2d));
    printf("   (Calculation: 4 rows * 17 columns * 1 byte)\n");

    return 0;
}