Strings

  • Sequence of characters enclosed in double quotes

  • A one-dimensional character array can be used to store a string (as long as it ends with a null character \0)

Declaration

  1. Vector declaration of a char vector with length length

char string_name[length];
  1. Dynamic allocation dynamic allocation of a memory area of length bytes, which is organized as a char sequence (1 Byte each)

char *string_name;
string_name=malloc(length);

Inizialization

  1. With implicit size

    char  string_name[] = "value";

    where the length of the string is:

    sizeof(string_name) - 1
  2. With explicit size

    char  nomeStringa[lenght] = "value";
    • if length >= (num_string_characters + 1), the string occupies the "value" number of characters + 1 (/0)

    • else KILLED PROCESS

Vector of strings

  1. With an array

    char  vector_name[array_size][string_size];
  2. With a pointer

    char **vector_name =NULL;
    vector_name=malloc(array_size * sizeof(char*));
    
    int i;
    
    for (i = 0; i<array_size; i++)
         vector_name[i] = malloc(sizeof(char)*string_size);

Initialization

  1. With an array

    char vector_name[array_size][string_size] = ["value1", "value2", ...];

    where:

    • array_size: number of strings in the vector (# of elements)

    • string_size: maximum number of characters for the strings

    One or both the parameters can be omitted and are retrieved automatically.

  2. With a pointer

    char *vector_name[string_size] = ["value1", "value2", ...];

    It implicitly calculates both the number of strings and the number of characters in each individual string (by evaluating the values on the left)

    char  **p =NULL;
    p=malloc(3 * sizeof(char*));
    
    int i;
    for (i = 0; i<3; i++)
         p[i] = malloc(sizeof(char)*3);

Last updated