Typically, you use
Code:
void takes_lines(char **const linearray, const size_t linecount)
{
/* The first line is at linearray[0],
* first character of second line is linearray[1][0],
* first character of third line is linearray[2][0],
* and so on.
* Only linearray[0] through linearray[linecount-1] are valid.
*/
}
The first const means the linearray variable is constant; the pointers to each line, and the contents of each line, are still modifiable. (If they are all constant, you can use const char *const *const linearray instead.)
The second const means the linecount variable is constant.
For a generic array of lines or strings, I tend to use (untested!)
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct {
size_t max_count;
size_t count;
char **line;
} lines;
#define LINES_INIT { 0, 0, NULL }
size_t lines_add(lines *const array, const char *const line)
{
const size_t linelen = (line) ? strlen(line) : 0;
char *lineptr;
if (!ref) {
fprintf(stderr, "lines_add(): NULL array!\n");
exit(EXIT_FAILURE);
}
if (ref->count + 1 >= ref->max_count) {
const size_t max_count = (ref_count | 63) + 65; /* Or just ref_count + N, N >= 2 */
void *const old = ref->line;
size_t i;
ref->line = realloc(old, max_count * sizeof *(ref->line));
if (!ref->line) {
free(old);
fprintf(stderr, "lines_add(): Out of memory.\n");
exit(EXIT_FAILURE);
}
ref->max_count = max_count;
for (i = ref->count; i < max_count; i++)
ref->line[i] = NULL;
}
lineptr = malloc(linelen + 1);
if (!lineptr) {
fprintf(stderr, "lines_add(): Out of memory.\n");
exit(EXIT_FAILURE);
}
if (linelen > 0)
memcpy(lineptr, line, linelen);
lineptr[linelen] = '\0';
/* Not necessary, I'm just paranoid */
ref->line[ref->count + 1] = NULL;
ref->line[ref->count] = lineptr;
return ref->count++;
}
You can combine these using e.g.
Code:
int main(void)
{
lines many = LINES_INIT;
lines_add(&many, "First line");
lines_add(&many, "Second line");
lines_add(&many, "Third line");
lines_add(&many, "Fourth line");
lines_add(&many, "Fifth line");
/* Calls takes_lines(), passes references to all lines */
takes_lines(many.line, many.count);
/* Passes a reference to the first three lines */
takes_lines(many.line, 3);
/* Passes a reference to last two lines */
takes_lines(many.line + many.count - 2, 2);
/* Passes a reference to first half of all lines */
takes_lines(many.line, many_count / 2);
/* Passes a reference to latter half of all lines */
takes_lines(many.line + many_count / 2, many_count - (many_count / 2));
/* Done. */
return EXIT_SUCCESS;
}