Arrays_and_Pointers
Mao
● Keyword: static ● Operators: & * (unary) ● How to create and initialize arrays ● Pointers (building on the basics you already know) and see
how they relate to arrays
● Writing functions that process arrays ● Two-dimensional arrays
Static variables have the property of preserving their value even after they are out of their scope! { Hence, a static variable preserves its previous value in its previous scope and is not initialized again }
in the new scope. The program on the right outputs: 1 2
// function with static variable int fun()
static int count = 0; count++; return count;
int main() {
printf("%d ", fun()); printf("%d ", fun()); return 0;
}
Consider the following example of array declarations:
/* some array declarations */ int main(void) {
float candy[365]; /* array of 365 floats */ char code[12]; /* array of 12 chars */ int states[50]; /* array of 50 ints */
...
}
Initialize an array by using a comma-separated list of values enclosed in braces.
int main(void) {
int powers[8] = {1,2,4,6,8,16,32,64}; /* ANSI C and later */ ...
}
Initialize an array by using a comma-separated list of values enclosed in braces.
int main(void) {
int powers[8] = {1,2,4,6,8,16,32,64}; /* ANSI C and later */ ...
}
The program initializes days[] with a list of comma-separated values enclosed in braces.
What if you fail to initialize an array?
If you partially initialize an array, the remaining elements are set to 0 .
With C99, you can use an index in brackets in the initialization list to specify a particular element.
Make sure you use array indices that are within bounds; that is, you have to make sure they have values valid for the array.
The compiler doesn’t check to see whether the indices are valid. The result of using a bad index is, in the language of the C standard, undefined.
Specifying an Array Size
float rain[5] [12]; // rain is an array of 5 somethings
This initialization uses five embraced lists of numbers, all enclosed by one outer set of braces. The data in the first interior set of braces is assigned to the first row of the array, the data in the second interior set goes to the second row, and so on. The rules we discussed about mismatches between data and array sizes apply to each row.
A pointer variable (simply called pointer) holds the memory address. Through the pointer, the dereference operator * can be used to access the actual value at a specific memory location.
Normally, a variable contains a data value—e.g., an integer, a floating-point value, and a character. However, a pointer contains the memory address of a variable that in turn contains a data value.
int count = 5; short status = 2; char letter = 'A'; string s = "ABC"; // c++ int* pCount = &count; short* pStatus = &status; char* pLetter = &letter; string* pString = &s; //c++ pCount = &count;
&: address operator &count means the address of count *: dereferencing operator *pCount means getting the value pointed by pCount. In other words, *pCount and count are equivalent in the above code.
A pointer can be initialized when it is declared or by using an assignment statement. However, if you assign an address to a pointer, the syntax is
rather than
*pCount = &count; // Wrong
Referencing a value through a pointer is often called indirection. The syntax for referencing a value from a pointer is
*pointer
For example, you can increase count using
(*pCount)++; // Indirect reference
or
A pointer variable is declared with a type such as int or double. You have to assign the address of the variable of the same type. It is a syntax error if the type of the variable does not match the type of the pointer. For example, the following code is wrong:
int area = 1; double* pArea = &area; // Wrong
Note that pointers can be compared using relational operators (==, !=, <, <=, >, >=) to determine their order.
(continuing)
Changes of values after assignments are made using pointer variables. Note that (b) and (c) show the same situation, and so do (d) and (e), (g) and (h), (i) and (j), (k) and (l), and (m) and (n).
A constant pointer points to a constant memory location, but the actual value in the memory location can be changed. For example:
double radius = 5; double* const p = &radius;
Here p is a constant pointer. It must be declared and initialized in the same statement. A new address cannot be assigned to p later. Though p is a constant, the data pointed to by p is not constant and can be changed. For example, the following statement changes radius to 10:
*p = 10;
Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to.
References (in C++) : A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is also implemented by storing the address of an object. A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e., the compiler will apply the * operator for you.
For example:
int i = 3; // A pointer to variable i or "stores the address of i" int *ptr = &i; // A reference (or alias) for i. int &ref = i; // This only works in C++
References should be declared and initialized references at a single step:
int a = 10; int &p = a; // It is correct in C++ // but int &p; p = a; // It is incorrect
| (C++) | ||
| (C++) | ||
https://www.geeksforgeeks.org/pointers-vs-references-cpp/
C allows you to access the elements in the array using the dereference operator. To access the first element, use *list. Other elements can be accessed using *(list + 1), *(list + 2), *(list + 3), *(list + 4), and *(list + 5).
Note that list should be treated as a constant so that any attempt to assign a value to list, as in list++, is considered a compilation error.
Algorithms and Data Structures - Mao © 2022 There is no failure just changeable code.
If flizny is an array, the following is true:
flizny == &flizny[0]; // name of array is the address of the first element
Both flizny and &flizny[0] represent the memory address of that first element. (Recall that & is the address operator.)
char s[] vs char *s
| char s[10] = “apple”; | char *p = “apple”; |
|---|---|
| s is an array | p is a pointer, “apple” is a constant |
| s and &s are the same. | p and &p are not the same. |
| s++ is not valid | p++ is valid |
| sizeof(s) // 10 here, array size | sizeof(p); // pointer size (4 or 8) |
| s[0] = ‘b’; // valid | p[0] = ‘b’; // invalid |
Note: An array name is an alias to the address of an array, and its address is defined as the address of the array itself.
As a result of C’s cleverness, we have the following equalities:
dates + 2 == &date[2] // same address *(dates + 2) == dates[2] // same value
The pointer start begins by pointing to the first element of marbles , so the assignment expression total +=* start adds the value of the first element (20) to total . Then the expression start++ increments the pointer variable start so that it points to the next element in the array. Because start points to type int , C increments the value of start by the size of int .
● Stephen Prata. C Primer Plus (6th Edition). Addison-Wesley
Professional, 2013.