Lecture 3 Flashcards
Arrays and Strings
for a single-dimensional array, can you have different data types?
no, all elements must be the same type
ex) int array –> only ints allowed
what is the sequence of elements in a single dimensional array?
contiguous aka ordered sequence
- no holes in the array, must be
elements at every index
is the size/length of an array fixed?
yes, the number of elements (N) is set when the array is created
ex) int a[5];
what index position is the first element in the array located at?
A[0]
what index position is the last element in the array located at?
A[N - 1], where N is the number of elements
single-dimensional array basic syntax
data_type name[size];
ex) int mol[5];
if you don’t initialize your array with values, will it be assigned to 0?
no, it will be assigned to whatever is leftover in memory at those address locations
**best to initialize upon creation
what happens in memory when you create an array and initialize it with values?
the right amount of memory will be allocated based on the size of the array and will be set to those values
how do you calculate how many bytes are allocated on the stack for an array?
number of elements (size) * size of data type
ex) int a[5]
int = 4 bytes
size = 5 elements
4 * 5 = 20 bytes allocated
how to find how many bytes are allocated on the stack for an array using code?
using sizeof( )
ex) int A[N];
int bytes = N * sizeof(int);
does c have a length property?
no
how to find the size of an array?
size = total # of bytes / size of data type
ex)
int size = sizeof(A) / sizeof(int);
- this returns the total number of bytes divided by the amount of bytes for each element –> gets size of array
is there array bound checking in c?
no
if you try to access an index in your array outside of the size of your array (int A[5]; –> say something like A[10]), what happens?
unpredictable behavior: may work, but a memory fault (aka segmentation fault) will likely occur
- memory access violation –> attempting to access a restricted area in memory
multi-dimensional array basic syntax
data_type name [size1] [size2]…size[N];