Arrays in C++ - Reading Assignment

Your example is an example of a struct :slight_smile:
The array can only hold data of the same type:

student s[5]; // array of 5 students :)
2 Likes
  • It is a single variable that hold different other variables, which can be accessed in a numeral order
  • 1, arrays start with 0
  • For a fixed array, you have to device before compiling how large the array is
1 Like
  • For example, When you are defining the array: int array[] = { 1,2,3 }
  • sizeof(array)
  • sizeof(arr) / sizeof(arr[0])
  • Undefined actions, you don’t know what might happen since C++ is not designed to handle this sort of action
1 Like

How are they different? Do you mean they have different types?

1 Like

Yes, exactly! Different types was what I meant :stuck_out_tongue:

But that is not true :stuck_out_tongue: arrays hold variables of the same type :wink:

1 Like

Part 1:

  1. An array is an aggregate data type that lets us access many variables of the same type through a single identifier.
  2. Index 1
  3. In an array variable declaration, we use square brackets ([]) to tell the compiler both that this is an array variable (instead of a normal variable), as well as how many variables to allocate (called the array length ).

Part 2:

  1. initializing an array involves putting curly brackets and the array content inside separated by commas. Empty braces initializes with 0 for each element.

  2. use the sizeof() function.

int arrayLength(array)
{
int length = sizeof(array)/sizeof(array[0]);

return length;
}
  1. you get undefined behavior.
1 Like

1. What is an array?

An array is an aggregate data type that lets us access many variables of the same type through a single identifier.

2. Which index would you use to access the 2nd variable in an array?

1

3. What can you say about the size of an array?

A fixed array (also called a fixed length array or fixed size array ) is an array where the length is known at compile time.

1.How can you initialize an array?

Via use of an initializer list . The following example initializes the array

int prime[5]{ 2, 3, 5, 7, 11 }; // use initializer list to initialize the fixed array

  1. How can you get the size of an array in bytes?

int array[5]{ 0, 1, 2, 3, 4 }; // explicitly define the length of the array

int array[]{ 0, 1, 2, 3, 4 }; // let the initializer list set length of the array

  1. How can you use the function sizeof in order to calculate the number of elements in an array?

The std::size() function from the header can be used to determine the length of arrays.

  1. What happens when you try to write outside the bounds of the array?

C++ does not do any checking to make sure that your indices are valid for the length of your array.
So if you try to insert a value in an element that is outside of the length of your array, you will get undefined behavior – For example, this could overwrite the value of another variable, or cause your program to crash.

1 Like

This are examples of two ways to initialize the array with a fixed length. What we want to know is the size of the array in bytes? :slight_smile:

Indeed there are helper functions that do that, but how would you determine the size of the array without it? :wink:

1 Like
#include <iostream>

using namespace std;

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9,0};
  int arrSize = sizeof(arr)/sizeof(arr[0]);
  cout << "The size of the array is: " << arrSize << endl;
  return 0;
}
1 Like

PART 1.

  1. Array is a group of one type variables represented by one identifier.
  2. Array[1].
  3. It could be fix or dynamic. Fix size array length must be know during runtime.

PART 2.

  1. Like that -> Array [5] {0,1,2,3,4};
  2. To get size of array in bytes: sizeof(array);
  3. To calculate length of array, some maths should be done:
    sizeof(array)/sizeof(array[0]); (size of array in bytes is divided by size of one element of array in bytes).
  4. It’s very likely that the program will crash, or cause undefined behavior, since another variable could be overtired.
1 Like
  1. An array is a collection of many variables of the same type (e.g. they’re all int, double etc.), labelled with a single identifier.

  2. To find the Mth index in an array of N elements where M <= N, we use the identifier of that array followed by the M-1 in square brackets.
    e.g. prime[1] for the 2nd prime number in int prime[N]{}

  3. Fixed arrays, naturally, have a fixed length (at compile time). This is often not helpful; we may want the caller to input data, and we wouldn’t know how large an array we would need. Fortunately there are also *dynamic arrays, with length that can be set at run time and have their length altered thereafter.

  4. You can initialize an array by inputting the elements of the fixed array using an initializer list.
    e.g. int prime[10]{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
    If some elements in the array are left uninitialized, then they are initialized to 0 for whatever fundamental type the array is listing
    e.g. int prime[6] 2.0, 3.0, 5.0, 7.0 } returns 2.0, 3.0, 5.0, 7.0, 0.0, 0.0
    This is known as zero initialization.

  5. You can find the size of an array in bytes using the following:

array size = array length * element size

  1. Using the above:

sizeof(array) = std::size() * sizeof(array[0])

where the std::size() function finds the length of an array. Rearranging for std::size():

std::size() = sizeof(array) / sizeof(array[0])

  1. Writing outside of an array is not checked by C++, so you may *accidentally add elements to an array and cause undefined behaviour such as overwriting or crashes.
1 Like
  1. What is an array?
    An array is an aggregate data type that lets us access many variables of the same type through a single identifier.

  2. Which index would you use to access the 2nd variable in an array?
    array[1]

  3. What can you say about the size of an array?
    How many elements (or variables) the array contains.

  4. How can you initialize an array?
    int array[5]{ 7, 4, 5 }

  5. How can you get the size of an array in bytes?
    sizeof(array)

  6. How can you use the function sizeof in order to calculate the number of elements in an array?
    sizeof(array) / sizeof(array[0]);

  7. What happens when you try to write outside the bounds of the array?
    Undefined behavior could occur. resulting in overwriting values of other variables or system crashes.

1 Like

Arrays in C++ - Part 1

  1. What is an array?
    An array is an aggregate data type that lets us access many variables of the same type through a single identifier.

  2. Which index would you use to access the 2nd variable in an array?
    Since the first element of an array has the index 0, the answer is 1.

  3. What can you say about the size of an array?
    The size of a fixed array must be a compile-time constant, which must be known at compile time. However there are also dynamic arrays in C++, but this kind array is a little more complicated to instantiate.

Arrays in C++ - Part 2

  1. How can you initialize an array?
    You can initialize entire arrays via use of an initializer list in C++. You can also initialize an entire array by using an empty initializer list. In this case all array elements will be set to 0 for integers, to 0.0 for doubles and to empty strings for string arrays.

  2. How can you get the size of an array in bytes?
    You can use the sizeof(array) statement to get the number of bytes used by the array in memory.

  3. How can you use the function sizeof in order to calculate the number of elements in an array?
    You can divide the number of bytes used by all elements of the array by the number of bytes used by one element of the array: sizeof(array) / sizeof(array[0]).

  4. What happens when you try to write outside the bounds of the array?
    This would overwrite the area in memory where this element would be, if the array had this much elements. But this could lead to undefined behavior, because the value of another variable stored at this location might be overwritten! Negative indices have the same effect. In this case some important value of another variable in the memory before the array may be affected.

1 Like
  1. It is a one dimensional collection of elements. The order is indexed and starts with a 0.
  2. 1
  3. In C++ is fixed at the declaration.

  1. Example: int myArray[5]={1,2,3,4,5};
  2. cout << sizeof(myArray); // it will be 20 byte if one element is 4 byte
  3. cout << sizeof(myArray)/4; // it will be 6 elements if the computer uses 4 bytes for one element
  4. It can cause “buffer overflow”.
1 Like
  1. What is an array?
    An array is an aggregate data type that lets us access many variables of the same type through a single identifier

  2. Which index would you use to access the 2nd variable in an array?
    Index 1

  3. What can you say about the size of an array?
    There are two types of array. Fixed and dynamic. Programmers allocate the size of a fixed array at launch.

  4. How can you initialize an array?
    One way to initialize an array is one element at a time.
    Another is with an iinitializer list.
    Int prime [5] {2, 3,5,6,11}; If there are more initializers in the list than the array can hold, the compiler will generate an error. If there are less, the remaining elements are initialized to 0 -called zero initialization.

  5. How can you get the size of an array in bytes?
    the size of the entire array is equal to the array’s length multiplied by the size of an element. Put more compactly: array size

  6. How can you use the function size of in order to calculate the number of elements in an array?
    sizeof(nameOfArray)/sizeOf(nameOfArray[0])

  7. What happens when you try to write outside the bounds of the array?
    Either: The array does not compile,
    or the value that is stored outside of the bounce will overwrite another piece of code that could crash the code.

  1. Declare an array to hold the high temperature (to the nearest tenth of a degree) for each day of a year
    (assume 365 days in a year). Initialize the array with a value of 0.0 for each day.
    Double temperature[365]{};
  2. Set up an enum with the names of the following animals: chicken, dog, cat, elephant, duck, and snake. Put the enum in a namespace. Define an array with an element for each of these animals, and use an initializer list to initialize each element to hold the number of legs that animal has.
    #include
    namespace Animals
    {
    enum animals {
    chicken,
    dog,
    cat,
    elephant,
    duck
    snake,
    max_animals
    };
    }
    int main()
    {
    int legs[animals::max_animals]{2,4,4,4,2,0};
    std::cout<<”An elephant has”<<legs[Animals::elephant]<<”legs.\n”;
    return 0;
    }
1 Like

Part 1

  1. An array is an aggregate data type that lets us access many variables of the same type through a single identifier.
  2. The 2nd variable is index 1.
  3. The size of an array is fixed at compile time for a fixed array.

Part 2

  1. You can initialize an array using an initializer list.

  2. std::cout << sizeof(array) << ‘\n’; // will print the size of the array multiplied by the size of an int

  3. We can use sizeof to find the number of bytes in the array and divide by the byte size of the data type we’re using, in the case below that’s an int.
    int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 };
    std::cout << sizeof(array) << ‘\n’; // will print the size of the array multiplied by the size of an int
    std::cout << sizeof(int) << ‘\n’;

  4. The program will write the value in the memory location that would have been used by the array if it had an index high enough. This means a location in memory possibly used by some other function or program has been corrupted by your program. Opps this is bad.

1 Like
  1. An array is a variable that stores multiple values

  2. arrayName[1];

  3. Its size is fixed by array length * element size

  4. int array[] = { 1,2, etc };

  5. sizeof(array);

  6. sizeof(array)/sizeof(array[0]);

  7. Throws an error

1 Like

In most cases this is true, but actually the behaviour is undefined. :slight_smile:

1 Like
  1. What is an array?
  • It is a data type that can contain several values under one identifier.
  1. Which index would you use to access the 2nd variable in an array?
  • Elements in an array are numbered starting from 0, so we would use [1].
  1. What can you say about the size of an array?
  • Arrays can be fixed, where we define their length:
    int arrayName [5] {};
    or dynamic, where compiler figures out the length by how many elements the array contains at the moment:
    int arrayName [] {};
    Dynamic is useful if we or the user or some function will insert some values in the array later.
  • We can access the array length with std::size (arrayName) if we #include < iterator > in the header. However, if we use this on an array that is passed to a function, we will get an error.
  1. How can you initialize an array?
  • int numbers [3] {3, 4, 5};
    or
  • int numbers [3] {};
    numbers [0] = 1;
    numbers [1] = 2;
    numbers [2] = 3;
  1. How can you get the size of an array in bytes?
  • With the sizeof (arrayName) operator.
  • If we use this on an array that is passed to a function, we will instead get the size of a pointer.
  1. How can you use the function sizeof in order to calculate the number of elements in an array?
  • We can find out the size of the array and the size of one element, and then divide:
    sizeof (arrayName) / sizeof (arrayName[0])
  • This only works for fixed arrays.
  • It must be done in the same function the array is declared in. I think they mean - in the same scope.
  • It is clear for integers or booleans, where value will always take the same amount of memory. I was wondering, though, if this also works for strings of various length, so I tried this:
    image
    As it turns out, all of the strings take 32 bytes and we can find out the length the same way.
  1. What happens when you try to write outside the bounds of the array?
  • The value will be saved where it would have been, if the array was longer. This means we could rewrite some other value that was already there, or take some unknown value from there. This, then, may cause unexpected results or crashes.
  • The same happens if we try to access negative positions like array[-1].
1 Like