pointer arithmetic

In the below example, the getline function returns the size of a line made of characters and stored in the line array. Now assuming we haven't hit max lines or buffer limit, we call strcpy, which takes takes the pointer p (which I assume is pointing to 0 at the moment) and takes the line array which is pointing at its first element.

Then we assign value of t to s and use pointer arithmetic to move to the next memory addresses. So let's say t had 5 characters. So that is 5 adjacent memory addresses. Therefore, we have to copy these 5 characters into memory addresses adjacent to the address p initially was pointing at. Therefore, when strcpy is done, p is pointing at a new memory address.

Then it seems like we only put the current address p is pointing at in the lineptr array of pointers. If that's the case, when we call writelines, how does printf know how many addresses are associated with the given pointer in lineptr to make sure it prints the right line.

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
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;
}

void strcpy(char *s, char *t) { 
    while (*s++ = *t++) 
        ; 
} 

void writelines(char *lineptr[], int nlines)
{
    int i;
    for (i = 0; i < nlines; i++)
        printf("%s\n", lineptr[i]);
}
Last edited on
Topic archived. No new replies allowed.