Arrays and Strings


Collapse Content

Arrays

//Arrays must be initialized with a concrete size.
char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes
int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
// (assuming 4-byte words)

// You can initialize an array to 0 thusly:
char my_array[20] = {0};

// Indexing an array is like other languages -- or,
// rather, other languages are like C
my_array[0]; // => 0

// Arrays are mutable; it's just memory!
my_array[1] = 2;
printf("%d\n", my_array[1]); // => 2

// In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
// can be declared as well. The size of such an array need not be a compile
// time constant:
printf("Enter the array size: "); // ask the user for an array size
char buf[0x100];
fgets(buf, sizeof buf, stdin);

// strtoul parses a string to an unsigned integer
size_t size2 = strtoul(buf, NULL, 10);
int var_length_array[size2]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);

// A possible outcome of this program may be:
// > Enter the array size: 10
// > sizeof array = 40

Strings

Strings are just arrays of chars terminated by a NULL (0x00) byte, represented in strings as the special character '\0'. (We don't have to include the NULL byte in string literals; the compiler inserts it at the end of the array for us.)

char a_string[20] = "This is a string";
printf("%s\n", a_string); // %s formats a string

printf("%d\n", a_string[16]); // => 0
// i.e., byte #17 is 0 (as are 18, 19, and 20)

// If we have characters between single quotes, that's a character literal.
// It's of type `int`, and *not* `char` (for historical reasons).
int cha = 'a'; // fine
char chb = 'a'; // fine too (implicit conversion from int to char)

//Multi-dimensional arrays:
int multi_array[2][5] = {
  {1, 2, 3, 4, 5},
  {6, 7, 8, 9, 0}
};
//access elements:
int array_int = multi_array[0][2]; // => 3

Challenge

For each word, you are given, print "Hello {word}!".
(Replace {word} with the given word).

In C++ (which we're using, despite this module being on C), you can use cout << variable to print variable to output and use '\n' for a newline. For example, cout << "Hello" << '\n'; will print "Hello" on a newline.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]