|
CS256 - Principles of Structured Design
Fall 2021
| 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
[] subscript:
char data[rows][cols];
data = {
{'.','.',... cols ...,'.'}, ┐
{'.','.',... cols ...,'.'}, ├── rows
... │
{'.','.',... cols ...,'.'} ┘
}
rows and cols should normally be constant values, however C allows dynamic
arrays:
char data[LINES][COLS];
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:
data[y][x] = '#'; // places '#' at row y, column x in the 2D data array.
The amount of space required for the array is rows * cols * sizeof(char) .
If the last subscript ([x] ) is omitted, then data[y] is the string of
characters at row y . i.e.:
printf("%s", data[y]);
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 * :
char *str; // A string (character) pointer
int *nums; // An integer pointer
char *strs[10]; // An array of 10 string pointers.
int **x; // A pointer to a pointer to an integer.
A pointer can be thought of an used like an array, however it does not
allocate space for any data by itself:
char s[10]; \ These are not the same, although they can be used in the
char *s; / same way.
char s1[] = "text";
char *s2 = "text";
In this case s1 allocates space for "text\0" which is copied into it, data
in s1 can be modified. s2 points to a read-only version of "text\0" ,
which can be read, but not modified.
To access the second character in s1 or s2 , you can use the array index
method:
s1[1] == 'e'
s2[1] == 'e'
For s2 however you can use the * operator to "dereference" the pointer
and get the data that it points to:
*s2 == 't' same as *(s2+0) == 't'
*(s2+1) == 'e'
*(s2+2) == 'x'
...
int strlen(char *s)
{
int len = 0;
while (*s != '\0') {
len++;
s++; // Move pointer to the next character
}
return len;
}
|