Arrays

For arrays under the hood, see Arrays

C and C++

int a[5] = {10, -7, 3, 8, 42};
int b[] = {10, -7, 3, 8, 42}; // Size is inferred
int c[5] = {1, 2, 3}; // Last 2 entries ase 0
int d[5] = {3}; // First item is 3, rest are 0
int e[5]; // Contains garbage entries
int a[5] = {[2] = 2, [4] = 3123}; // Spicified the third and fifth entries, rest are 0
This is not allowed

int a[5];
a = {1, 2, 3, 4, 5};
// Nor is
a[5] = {1, 2, 3, 4, 5};

Sizeof

#include <stdio.h>

int main() {
    int a[] = {-1, 2, 1, 2, -4, 1}; // Length 6

    // Divide the total size of the array by the size of 1 element to get the number of elements
    printf("%zu\n", sizeof(a) / sizeof(a[0])); // 6

    printf("%zu %zu %zu %zu\n",
        sizeof(char), // 1
        sizeof(int),  // 4
        sizeof(a[0]), // 6
        sizeof(a)     // 24
    );

    return 0;
}

Dynamic Arrays

Using Dynamic Memory Allocation,

Example

int *numbers(int n) {
    int *p = malloc(n * sizeof(int));

    assert(p); // Verify that malloc succeeded

    for (int i = 0; i < n; i++) {
        p[i] = i;
    }

    return p;
}

// Deleting
int main() {
    int *arr = malloc(5 * sizeof(int))

    assert(arr);
    free(arr);
}

C++

Dynamic Arrays

Using the New Keyword,

Example

int *numbers(int n) {
    int *p = new int[n];

    for (int i = 0; i < n; i++) {
        p[i] = i;
    }

    return p;
}

// Deleting
int main() {
    string* arr = new string[5];

    delete []arr;
}