About Lesson
Pointers can be stored in arrays as well just like other variables, since they are variables themselves. Let’s look the at following set of functions where we use an array of pointers to store multiple input lines of variable lengths efficiently and conveniently.
#define MAXLEN 100 #define MAXLINES 1000 /* Read a line of text, not exceeding maxlen, into line. */ int readline(char *line, int maxlen) { int ch, count = 0; while (count < maxlen - 1 && (ch = getchar()) != 'n') line[count++] = ch; line[count] = '\0'; return count; } /* Read multiple lines of text, not exceeding maxlines, * using readline() and put it into lines, which is an * array of char pointers. malloc is used here to allocate * dynamic memory to store the string. This function is * defined in the header file "stdlib.h". We need to * free this dynamically allocated memory after its use * using free() */ int readlines(char *lines[], int maxlines) { int count = 0; int len; char line[MAXLEN]; while (count < maxlines - 1 && (len = readline(line, MAXLEN)) > 0) { char *ptr = (char *)malloc(len + 1); strcpy(ptr, line); lines[count++] = ptr; } return count; } /* Print each line in lines */ void printlines(char *lines[], int line_count) { int i; for (i = 0; i < line_count; i++) printf("%s\n", lines[i]); } /* Free the dynamic memory used by each element in lines */ void freelines(char *lines[], int line_count) { int i; for (i = 0; i < line_count; i++) free(lines[i]); }
Our main function could look like this:
int main() { char *lines[MAXLINES]; int line_count; line_count = readlines(lines, MAXLINES); printlines(lines, line_count); freelines(lines, line_count); return 0; }
The declaration
char *lines[MAXLINES];
says that lines is an array of MAXLINES elements, each element being a pointer to a char. So, lines[i] is a character pointer.