Tuesday, July 2, 2019

CS2100: Arrays and TypeStruct

Arrays

It's illegal to assign an array to another array.

#define N 10
int source[N] = { 10, 20, 30, 40, 50 };
int dest[N];
dest = source;  // illegal!
This is due to the array name being a constant pointer, it points to the first element of the array
This cannot be changed.

If we want to do this, we have to write a loop...

All array names point to the first element of the array memory.
We don't need to pass the pointer of the array to a function since the name itself is already an array.

Strings

All strings are character array that ends with "\0" which is a null character with a ASCII value of zero.
Without this character, it's just an array of character.
1. char fruit_name[] = "apple";
2. char fruit_name[] = {'a','p','p','l','e','\0'};

Reading Strings from stdin:
fgets(str, size, stdin) // reads size – 1 char,
                 // or until newline
Note: It will read a newline character, thus we need to replace it will "\0" 
e.g the string "eat" will be {'e','a','t','\n','\0'}
scanf("%s", str);  // reads until white space
Printing:
puts(str);  // terminates with newline
printf("%s\n", str);

Structures

A type is not a variable and needs to be defined before declaring variables for that type.
No memory is allocated to a type.

Declaration:

Initialisation:
result_t result1 = { 123321, 93.5, 'A' };

We can also use the dot operator, it acts like an object in java
result_t result2;
result2.stuNum = 456654;
result2.score = 62.0;
result2.grade = 'D';
However, when reading, we need to use the address when reading the values.
scanf("%d %f %c", &result1.stuNum, &result1.score,
                  &result1.grad
e);
Use the name to refer to the entire structure and the dot operator to refer to an individual member.
Unlike arrays, we can do assignments. ie result2 = result1;

Structures can also be returned as return types from functions.

The arrow operator:
Instead of using the dot, we can use "->" as a shortcut
(*player_ptr).name is equal to player_ptr->name

(*player_ptr).age is equal to player_ptr->age 

We cannot forget the brackets as the dot is higher precedence than * thus removing the bracket will cause the dot to be evaluated first. Ie. it be read as *(player_ptr.name) instead


Note: When passing to functions,
if we want to edit the data, we need to pass in the memory referenced by &(Name of data)
and in the function, referenced by *(Name of data) and assess it by (*nameofdata).variable1.
However, if we are not altering the data, there's no need to pass in the reference.


<Prev 3. Pointers

No comments:

Post a Comment