Searching an array with pointers

This is a discussion on Searching an array with pointers within the C Programming forums, part of the General Programming Boards category; So I think I am finally getting the hang of pointers. I even made a simple program to swap values ...

  1. #1
    Registered User
    Join Date
    Feb 2004
    Posts
    73

    Searching an array with pointers

    So I think I am finally getting the hang of pointers. I even made a simple program to swap values of pointers through a function. I know, simple, but it was just a way of making sure I knew what I was doing. I am still having trouble with pointers and arrays though.

    Take a look at this problem:

    Write the following function:

    int search (int a [], int n, int key);

    a in an array to be searched, n is the number of elements in the array, and key is the search key. search should return 1 if key matches some element of a, 0 if it doesnít.

    Suppose you have an array of 10 numbers with the following values: 10, 20, 13, 32, 50, 25, 40, 49, 11, 12. Use the search function you made earlier to print out whether the values 10, 145, 15, and 11 exist in the array. Write this section in main.


    Now then.. The signature of the function must remain the same, and I am getting stuck.

    The only thing I have so far is this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int search (int a [], int n, int key){
    int b;
    for(b=0; b<=n; n++){
                                    /*search for values with pointer*/
    
    }
    
    int main()
    {
    int array[]={10, 20, 13, 32, 50, 25, 40, 49, 11, 12};
    
    search(array[]);                        /*run function with values*/
          system("PAUSE");
          return 0;
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You'll actually want to do:
    Code:
    for( b = 0; b<n; b++ )
    Then, all you have to do is check each element in the array to see if it matches your key. Something like:
    Code:
    if( a[b] == keyvalue )
    You're using b as the array index, as you step through it each element at a time. So that's what you use to increment (or decrement if you were starting at the other end).

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    Hmm

    I just found out this about the problem too:

    "Use the function 4 different times to check. Please donít change the signature of any function."

    So I guess it wants a pointer to be defined in main and set equal to the numbers at different points in time then calling the function after each time.

    Thats my guess, although I coulud be going in the wrong direction on this.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It sounds like all you have to do is call it four times to check for four different things:
    Code:
    search( array, size, 10 );
    ...two more...
    search( array, size, 11 );
    Call the same function multiple times with different key values. (Assuming the key value, the last parameter, is what you're looking for.) Naturally you'll need to check the return value of the function, I omitted that step.
    [edit]
    Here is an example:
    Code:
    int myfun( char *s )
    {
        printf("%s", s );
        return 0;
    }
    
    int main( void )
    {
        myfun( "Hello " );
        myfun("there, " );
        myfun("how " );
        myfun("are " );
        myfun("you?\n" );
        return 0;
    }
    That's what they mean by using the same function more than once without changing its signature. You're calling the same function over and over, you're just passing it something different each time. In your case, you're just changing what you search for.
    [/edit]

    Quzah.
    Last edited by quzah; 03-23-2004 at 04:00 PM.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    Thats what I am working on right now. Im gonna try finish what I have and see if it works. Ill post my progress in a few minutes.

  6. #6
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    This is what I have so far, although I am getting a bunch of errors with it. I think it is with the pointer, of course:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define TRUE 1
    #define FALSE 0
    int search (int a [], int n, int key){
    int b;
    for(b=0; b<n; b++){
       if (key==*(a+b)){
           return 1;}
       else{
           return 0;;}                             /*search for values with pointer*/
    }
    }
    
    int main()
    {
    int *ptr, k, j=9;
    int array[]={10, 20, 13, 32, 50, 25, 40, 49, 11, 12};
    
    ptr=&k;
    
    k=10;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}
    k=145;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}
    k=15;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}
    k=11;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}                        /*run function with values*/
          system("PAUSE");
          return 0;
    }
    FOUDND AN ERROR. NOW RUN. Still many errors though
    Last edited by pxleyes; 03-23-2004 at 04:12 PM.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    What specificly do you need a pointer for? Is it a requirement? Usually you use a pointer to:
    1) Pass large amounts of information around.
    2) Pas a value to a function so it can change it without having to return it via return.

    Without totally doing it for you, try this example:
    Code:
    int function( int array[], int size )
    {
        int x = 0;
        for( x = 0; x < size; x++ )
            printf("array[%d"] holds %d", x, array[x] );
    }
    
    int main( void )
    {
        int array[3] = { 5, 99, -1 };
        function( array, 3 );
    
        return 0;
    }
    Take a look at that, and see if you can get yours to function similarly. You don't need a pointer for what you're doing. If you really want to use one, then this is how a pointer to a variable works:
    Code:
    void function( int *ptr )
    {
        /* here we dereference the pointer to see what it holds */
        printf("in function, ptr = %d\n", *ptr );
    
        /* here we change what pointer points to, making that value different */
        *ptr = 1000;
    
        /* here we dereference the pointer to see what it holds */
        printf("in function, ptr = %d\n", *ptr );
    }
    
    int main( void )
    {
        int x = 5;
    
        printf("x holds %d\n", x );
        function( &x );
        printf("x now holds %d\n", x );
    
        return 0;
    }
    Perhaps those will be of some help. Rather than just fix your problems directly, if you know why it does what it does, you'll be better off in the long run.

    [edit]
    Ok, I see what you're doing. You want to use pointer math rather than referencing the cells of the array individually. In your case, you only want to return 0; if you reach the end of the array without finding the match. Try getting rid of else, and moving the return 0; to the end of the function, outside of the for loop.

    Also, you don't need to be passing a pointer to your function. If you want to pass a pointer, you can do it two ways:
    Code:
    int function( int *aptr )
    {
        ...do whatever...
    }
    
    int main( void )
    {
        int value = 5;
        int *ptr = &value;
    
        function( &value );
        function( ptr );
    
        return 0;
    }
    If you are passing a variable that isn't a pointer to a function that takes a pointer, you have to use the address-of operator in front of it, like the first example. If you are passing a pointer to a function that takes a pointer, you just pass its name, like you would with a regular non-pointer variable call.
    [/edit]

    Quzah.
    Last edited by quzah; 03-23-2004 at 04:22 PM.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    The thing is, the whole assigment, not just this, is about pointers. The first thing they said was "you should use pointer arithmetic (not array subscripting) to visit the array elements; you will lose all credit if you use array subscripting."

    So that is my attraction to pointers in this instance. I am getting an error with the passing of array[] in the function call. I dont know why that is.


    [/edit]
    The thing is, the program question says to return 0 if you dont find the value, thats why I still keep it there. Read the first post for info on that.
    Last edited by pxleyes; 03-23-2004 at 04:23 PM.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You still need it at the end of the loop. Walk though the code on paper and see what happens your way:
    Code:
    for( x = 0; x < arraysize; x++ )
        if( *(array+x) == tofind )
            ...yes, you have a match, so return 1
        else
            ...uh oh! If I return now, it will stop looping through the array now.
    
    ...if I return 0, now, I'm at the end of the array and I haven't found my match.
    Because if it had found a match, it would have returned 1 earlier.
    That's why you only return 0 at the end. Otherwise:
    Code:
    array[] = { 1, 2, 3 }
    If we were looking for 2, the if check would fail on the 1, so if you had return 0 inside the loop, it would immediately stop. You want it to only stop if you reach:
    a) The right value.
    b) The end of the loop without finding anything.

    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    OK, I get that part now.

  11. #11
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    Well, I am still left with this, and it isn't working.:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define TRUE 1
    #define FALSE 0
    #define N 10
    int search (int a [], int n, int key){
    int b;
     for(b=0; b<n; b++){
       if (key==*(a+b)){
           return TRUE;}
                                    /*search for values with pointer*/
     }
       else
           return FALSE;
    }
    
    int main()
    {
    int *ptr, k, j=9;
    int array[]={10, 20, 13, 32, 50, 25, 40, 49, 11, 12};
    
    *ptr=k;
    
    k=10;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}
    k=145;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}
    k=15;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}
    k=11;
    search(array[],j,&ptr);
    if (return==TRUE){
      printf ("%d does exist", *ptr)}
    else if(return==FALSE){
      printf ("%d does not exist", *ptr)}                        /*run function with values*/
          system("PAUSE");
    }
    I am still getting an error with the function call and the array.

  12. #12
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    Yea. Im not gonna post my source again becuase the changes are minimal, but I cant seem to get the function call to work. It says there is an error with the array in the function call.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    In the future, it's helpful to post the actual error you're getting. However, in this case, I've already shown you how to pass pointers. Read the example where I pass two pointers to function above to see what is wrong.

    But specificly, here is your problem:
    Code:
    *ptr=k;
    
    k=10;
    search(array[],j,&ptr);
    You should probably re-read the pointer section in your lessons or book. But for an answer, you're confused on how pointers work, or rather, how to pass them and assign to them. Try this example, understand what is going on, then revisit your program:
    Code:
    int main( void )
    {
        int y = 0; /* put a value of 0 in y */
        int x = 10; /* put a value of 10 in the variable x */
        int *ptr = NULL; /* make a new pointer, which points to nothing */
    
        ptr = &x; /* put the address of x in the pointer ptr */
    
        y = *ptr; /* dereference ptr, to get the value of what it points at. Put that in the variable y */
    
       printf("y is %d", y );
    }
    Before you run this program, ask yourself what y will end up holding. Then run the program, and see if you were right.

    In short:

    Pointers store addresses.
    To get the address of a non-pointer variable, you use the address-of operator. This is the & symbol.
    To get access to what is being pointed to, you dereference a pointer. To dereference a pointer, you use the * symbol.
    Only dereference pointers which are already pointing at something.

    Also, look at my previous examples of passing pointers to functions.

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    The pointer isn't giving me the problem. It is the array:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define TRUE 1
    #define FALSE 0
    #define N 10
    int search (int a [], int n, int key){
    int b;
     for(b=0; b<n; b++){
       if (key==*(a+b)){
           return TRUE;}
                                    /*search for values with pointer*/
     }
       else
           return FALSE;
    }
    
    int main()
    {
    int *ptr, k, j=9;
    int array[]={10, 20, 13, 32, 50, 25, 40, 49, 11, 12};
    
    k=10;
    search(array[],j,10);
    if (search(array[],j,10)==TRUE){
      printf ("%d does exist", k)}
    else if(search(array[],j,10)==FALSE){
      printf ("%d does not exist", k)}
    k=145;
    search(array[],j,145);
    if (search(array[],j,145)==TRUE){
      printf ("%d does exist", k)}
    else if(search(array[],j,145)==FALSE){
      printf ("%d does not exist", k)}
    k=15;
    search(array[],j,15);
    if (search(array[],j,15)==TRUE){
      printf ("%d does exist", k)}
    else if(search(array[],j,15)==FALSE){
      printf ("%d does not exist", k)}
    k=11;
    search(array[],j,11);
    if (search(array[],j,11)==TRUE){
      printf ("%d does exist", k)}
    else if(search(array[],j,11)==FALSE){
      printf ("%d does not exist", k)}                        /*run function with values*/
          system("PAUSE");
    }

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Trim the extra curly brace in search.

    Change this
    Code:
    search(array[],j,10);
    to this
    Code:
    search(array,j,10);
    everywhere execpt the definition of array[].

    Add the missing semicolons to your printf statements. [edit]You may want to add newlines to the format string too.
    Last edited by Dave_Sinkula; 03-23-2004 at 05:04 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. two-dimensional dynamic array of pointers to classes
    By Timo002 in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 07:18 AM
  2. how do i declare array of pointers to base clase reobject
    By icantprogram in forum C++ Programming
    Replies: 3
    Last Post: 12-20-2002, 02:30 AM
  3. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 09:31 AM
  4. Loading an array using pointers
    By cheesehead in forum C++ Programming
    Replies: 5
    Last Post: 12-10-2001, 05:23 AM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 10:48 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21