MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Declaration of Strings

In C, strings are groups of characters enclosed in quotation marks, declared as character arrays, and terminated with a '\0' (Null character). A character uses one byte in memory, whereas a single character string requires two bytes. Strings are declared with the char data type followed by the array size in square brackets, e.g., char name[20];

Strings in C can be initialized using a character array, such as char name[8] = {'P', 'R', 'O', 'G', 'R', 'A', 'M', '\0'};. Each character occupies 1 byte of memory, though the size can vary with different computer architectures. Characters in a string are stored in contiguous memory locations. The C compiler automatically inserts a null character (\0) at the end of the string, making manual initialization of the null character optional.

You can set the initial value of a character array using a string literal. If the array is too small, the literal will be truncated; if the literal is smaller, the remaining characters are undefined. If no size is specified, the array size is set to the literal's length, including the null terminator.

Examples:

  • char str[4] = {'u', 'n', 'i', 'x'}; is valid but problematic because it's not null-terminated.
  • char str[5] = {'u', 'n', 'i', 'x', '\0'}; is correct and null-terminated.
  • char str[4] = "unix"; is problematic as it lacks space for the null-terminator.
  • char str[] = "UNIX"; is correct as the compiler sets the appropriate size and adds the null-terminator

  • String constants

    String constants (enclosed in double quotes) can be assigned to char pointers or copied to char arrays.

    Example:

    char *s = "hello";

    char s[100];

    strcpy(s, "hello");


    Differences in Behavior

    1. In char *s = "hello";, s points to the string constant in the string constant table, making it read-only.
    2. In char s[100]; strcpy(s, "hello");, the string is copied into the array s, making it modifiable.
    3. Direct assignment s = "hello"; is not allowed for arrays and will not compile.


    /* Fragment 1 */

    {

    char *s;
    s = "hello";
    printf("%s\n", s);
    // Output: hello
    }

    /* Fragment 2 */
    {
        
    char s[100];
        strcpy(s, "hello");
        
    printf("%s\n", s);
      
    // Output: hello

    }


    Display of strings using different formatting

    The printf function with the %s format is used to display strings. For example, printf("%s", name); displays the entire string stored in name.

    To specify the accuracy and width, such as displaying the first 5 characters within a field width of 15, use:

    printf("%15.5s", name);

    Including a minus sign in the format (e.g., %-10.5s) left-justifies the string:

    printf("%-10.5s", name);

    Report an issue

    Reporting: Declaration of Strings (topic)

    Related Posts