pointers and arrays

The book states the following two are equivalent:

1
2
char s[];
char *s;


Since the name of an array is a synonym for the location of the initial element, the assignment pa=&a[0] can also be written as pa = a;

Given that knowledge, in the below example, we declare and initialize a pointer lineptr which points to the address of the first element of the char array. But why in the readlines function, the parameter list has this "char *lineptr[]". If *lineptr points to the first address of the array and lineptr[] also points to the first address of the array, why do we need to use both of them here? Why can't the argument list just contain *lineptr without the []?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */

int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

main()
{
    int nlines;		/* number of input lines read */

    if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
        ...
    } 
}

/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
    int len, nlines;
    char *p, line[MAXLEN];

    nlines = 0;
    while ((len = getline(line, MAXLEN)) > 0)
        if (nlines >= maxlines || p = alloc(len) == NULL)
           return -1;
        else {
            line[len-1] = '\0'; /* delete newline */
            strcpy(p, line);
            lineptr[nlines++] = p;
        }
    return nlines;
}
Since foo[] is the same as *foo,
then *foo[] is the same as **foo.

lineptr is an array of pointers to char.

You can make it more explicit by using typedefs:

1
2
3
4
5
typedef char *pchar;

pchar lineptr[MAXLINES];

int readlines(pchar lineptr[], int nlines);

That is, each element of the array is itself a pointer.

Hope this helps.
Topic archived. No new replies allowed.