CPlusPlus / Built-In Arrays

CPlusPlus / Built-In Arrays#

  1. What is an array?

    An array in C++ is a fixed-size, contiguous block of memory that stores multiple elements of the same data type. It’s a fundamental data structure that allows you to store and access multiple items using a single variable name and an index. Key characteristics of C++ arrays: a. Fixed size (cannot be resized after declaration) b. Elements are stored in contiguous memory locations c. All elements must be of the same data type d. Provides fast, constant-time access to elements using their index

  2. How do you copy an array?

    In C++, there’s no built-in way to directly copy one array to another using simple assignment. Here are a few methods to copy an array: a. Using a loop: for (int i=0; i<100; ++i) x[i]=y[i]; // copy 100 ints b. Using std::copy (from ): std::copy(y,y+100, x); // copy 100 ints c. Using memcpy (for non-object types): memcpy(x,y,100sizeof(int)); // copy 100sizeof(int) bytes

  3. How do you initialize an array?

    There are several ways to initialize an array in C++: a. Initializer list:

    int arr[5] = {1, 2, 3, 4, 5};
    

    b. Partial initialization (remaining elements are zero-initialized):

    int arr[5] = {1, 2, 3}; // arr will be {1, 2, 3, 0, 0}
    

    c. Zero initialization:

    int arr[5] = {0}; // All elements set to 0
    

    d. Omitting the size (array size is determined by the initializer):

    int arr[] = {1, 2, 3, 4, 5}; // Size is automatically set to 5
    

    e. Default initialization (values are indeterminate for fundamental types):

    int arr[5]; // Elements have indeterminate values
    

    f. Using a loop (for dynamic initialization):

    int arr[5];
    for(int i = 0; i < 5; i++) {
        arr[i] = i * 2; // Initialize with even numbers
    }
    
  4. What happens if you try to access an array element outside its bounds?

    Undefined behavior; it may cause a runtime error or access unintended memory.

  5. How can you calculate the number of elements in an array?

    sizeof(arr) / sizeof(arr[0])

  6. What’s the relationship between arrays and pointers in C++?

    Array names can decay into pointers to their first elements.

  7. Can you change the size of a built-in array after declaration?

    No, built-in arrays have a fixed size after declaration.

  8. What’s the difference between int arr[] and int arr in a function parameter?*

    They’re treated the same by the compiler, but int arr[] is more indicative of an array.

  9. What’s the proper way to return an array from a function?

    You can’t return a built-in array directly. Use std::array, std::vector, or return a pointer.