简体   繁体   中英

C programming… Linked List Pointer Iteration

Hello I have the following functions defined:

head();
traverse(struct *);

I'm concerned that when iterating through the list it is being modified.

void tail()
{
    n3.next = (struct entry*) 0xff;
}

void traverse(struct entry *listPt)
{
    while(listPt != (struct entry *) 0xff)
    {
        printf("%i\n", listPt->value);
        listPt = listPt->next;
    }
}

Should I use a different algorithm to iterate the list? Is it more beneficial to copy the list?

Is the following expression from the while loop overwritten existing (values) memory?

listPt = listPt->next;

The statement overrides only local variable listPt declared as a function parameter

struct entry *listPt

It does not modify the list itself.

Function parameters are its local variables. The function deals with copies of its arguments. Any changing of a parameter does not influence on the corresponding argument.

Consider

#include <stdio.h>

void func( int *p )
{
    int y = 20;

    p = &y;

    printf( "%d\n", *p );  // prints 20
}

int main( void )
{
    int x = 10;
    int *px = &x;

    printf( "%d\n", *px );    // prints 10;

    func( px );

    printf( "%d\n", *px );    // prints 10;
}

No this algorithm is ok, you wont modify the list. If you want to modify you have to set the function header like this void traverse(struct entry * & listPt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM