Returning a Pointer from a Function - C Function

C examples for Function:Function Return

Description

Returning a Pointer from a Function

Demo Code

#include <stdio.h>

struct Node{/*from  w w  w  .  j a va 2 s .c  o  m*/
    int value;
    struct Node *next;
};

struct Node *findNode (struct Node *listPtr, int match){
    while ( listPtr != (struct Node *) 0 )
        if ( listPtr->value == match )
            return (listPtr);
        else
            listPtr = listPtr->next;

    return (struct Node *) 0;
}

int main (void)
{
    struct Node n1, n2, n3;
    struct Node *listPtr, *listStart = &n1;

    int search;

    n1.value = 1;
    n1.next = &n2;

    n2.value = 2;
    n2.next = &n3;

    n3.value = 3;
    n3.next = (struct Node *) 0;   // mark list end with null pointer

    printf ("Enter value to locate: ");
    scanf ("%i", &search);

    listPtr = findNode (listStart, search);

    if( listPtr != (struct Node *) 0 )
        printf ("Found %i.\n", listPtr->value);
    else
        printf ("Not found.\n");

    return 0;
}

Related Tutorials