Reading:
2 Dimensional Arrays:A text file can be thought of as a 2D grid of characters (lines x columns)
If a single array is linear, i.e. 1 dimensional, then an array of arrays
is 2 dimensional (i.e. 2D). An array of array is defined by adding a second
rows and cols should normally be constant values, however C allows dynamic arrays:
Note: You may not attempt to initialize a dynamic sized array however. A single character can then be accessed in almost the same way that screen coordinate would be:
The amount of space required for the array is If the last subscript (
Reading a text file into a 2D array:
```
// Define outside of a function:
#define MAXLINES 200
#define MAXCOLS 120
// Inside of a function:
// Open the file (for reading):
FILE *fp = fopen("file.txt", "r");
// Define space for the rows and columns of data:
int lines[MAXLINES][MAXCOLS];
int line = 0;
// Read a line at at time from the file:
while(fgets(lines[line], MAXCOLS, fp) != NULL) {
line++;
if (line >= MAXLINES) break; // Stop when there is no more room in the array.
}
```
Pointers:A pointer is a variable that points to a storage area rather than defining a storage area itself. Pointers can be incremented to move to the next available storage area in memory as well. A pointer variable is defined with a leading
A pointer can be thought of an used like an array, however it does not allocate space for any data by itself:
In this case To access the second character in
For
```
int strlen(char *s)
{
int len = 0;
while (*s != '\0') {
len++;
s++; // Move pointer to the next character
}
return len;
}
```
|