lotoflaugh
lotoflaugh

Reputation: 63

Trouble with pointer, that can't explain in title

When it award lineptr[nlines++] = p , in next lap of loop that do again ,lineptr[nlines++] = p , does lineptr[--nlines] (element of lineptr[] , one element before who p pointed to) , will he change because p changed. I try with simple example, with some integers to try realize this , but it gave me different "result"? I found this example, lineptr[nlines++] = p , in k&r book.

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 = malloc(len)) == NULL)
  return -1;
else {
  line[len - 1] = '\0';  /* delete the newline */
  strcpy(p, line);
  lineptr[nlines++] = p;
                 }                       
return nlines;  
}

Upvotes: 2

Views: 76

Answers (2)

wimh
wimh

Reputation: 15232

If I understand you correctly, you basically ask about the following situation:

char *lineptr[];
char *p;
int nlines=0;

// first loop
p = malloc(len);
strcpy(p, line);
lineptr[nlines++] = p;  // will assign lineptr[0]

// second loop
p = malloc(len);
strcpy(p, line);
lineptr[nlines++] = p;  // will assign lineptr[1]

The second loop does not change anyting in lineptr what was assigned in the first loop.

p stores the result of malloc(), which is a pointer to some memory. Every call to malloc will point to different memory. When you reassign p, the previous value is lost, so it cannot change anything any more where it was pointing to before. And lineptr will never point to p, but it will be a copy of p at the moment of assignment.

My example above can also be written as:

char *lineptr[];
int nlines=0;

// first loop
lineptr[nlines] = malloc(len);  // will assign lineptr[0]
strcpy(lineptr[nlines], line);  
nlines++;

// second loop
lineptr[nlines] = malloc(len);  // will assign lineptr[1]
strcpy(lineptr[nlines], line);
nlines++;

Let me know if it is not clear yet.

Upvotes: 3

Dmitri
Dmitri

Reputation: 9375

If I understand correctly, you're asking whether changing the value of p to use in the next loop pass modifies the array element that was set to p's value in the previous pass... and the answer would be no. When each array element is assigned:

lineptr[nlines++] = p;

it becomes a copy of whatever value p has at the time of the assignment... changing p (the pointer value) later doesn't modify the array element. If you had changed what p points to without changing p itself, things would be different since the array element would still point to the same data.

Upvotes: 4

Related Questions