Thread: Array of pointers program help please!

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    166

    Array of pointers program help please!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    //#include <crtdbg.h>  // do not remove
    
    #define FLUSH while (getchar() != '\n')
    #define MEM_ERROR printf("Not enough memory!\n")
    
    // Prototype Declarations
    double getNum(void);
    double insertionSort(double *ptr, int counter);
    
    int main (void)
    {
    int *ptr;
    int **pptr;
    int counter;
           //  Local Definitions
           //  Statements
           printf("\t\t Homework 3 - Pointer Applications:\n"
                      "\t\t    Insertion Sort and Pointers\n\n" );
           if(!(pptr = malloc(1000 * sizeof (*ptr)))){
                   printf("Not enough memory available.\n"); // no memory available
                   exit(100);
           }
    
           if(!(ptr = malloc(1000 * sizeof ( double )))){
                   printf("Not enough memory available.\n"); // no memory available
                   exit(100);
           }
    
           getNum();
           insertionSort(&ptr, counter);
    
           //  printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n");  // do not remove
           printf("\n\t\tEnd of Program\n"
                      "\n\t\tHave a great day!\n");
    
           return 0;
    
    }
    
    /************************************************
     Prompt the user to enter a valid integer number
     Pre: nothing
     Post: returns a valid integer
    */
    double getNum(void)
    {
           double num;
           double number;
           double* p_walker;
           int counter;
           double *ptr;
           double **pptr;
    
           while (scanf("%lg", &num) != 1)
           {
                         // scanf returns 1 if number read corrrectly
               FLUSH;    // to "consume" the invalid input
              printf("-*- Invalid number. Please re-enter: ");
           } // while
           printf("\nPlease enter numbers and enter -1 when you are done: ");
           number = getNum();
           p_walker = ptr;
          while(number!= -1){
                   *p_walker = number;
                   pptr[counter] = p_walker;
                   printf("entered1: %lg \n", number);
                   printf("entered: %lg \n", *p_walker);
                   number = getNum();
                   p_walker++;
                   counter++;
    
           }
    
                   printf("endpointer = %ld startPointer = %ld Counter = %d\n", p_walker, ptr, counter);
           ptr = realloc(ptr, counter * sizeof(double));
           if( ptr == NULL )
              MEM_ERROR;
           else
              ptr = ptr;
    
    
           int i;
           for (i = 0; i < counter; i++) {
                   //printf("%lg\t",*(ptr+i));
                   printf("%lg\t", *(*pptr + i));
           }
    
       return num;
    }
    
    double insertionSort(double *ptr, int counter)
    {
    int i, j;
    double temp;
    
           for(i = 1; i < counter; i++)
           {
                   temp = ptr[i];
                   j = i - 1;
                           while(temp < ptr[j] && j >= 0)
                           {
                                   ptr[j + 1] = ptr[j];
                                   j = j - 1;
                           }
                   ptr[j + 1] = temp;
           }
    
           printf("\n The ascending order of the list is: \n");
           for (i = 0; i < counter; i++)
           {
                   printf("\n%d", ptr[i]);
           }
    
    
    
    }
    -When I try to run it, the compiler tells me: "passing argument 1 of 'insertionSort' from incompatible pointer type". What is the problem? Also, I'm pretty sure that there are a bunch of other things wrong with this program, so if you see some other stuff, please feel free to point them out.
    -Sorry if this program is a hot mess. Its a work in progress and not really even close to finishing. Thank you for your time!

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Manitoba, Canada
    Posts
    12
    Have you actually got this working before? From what I'm reading this doesn't make any sense.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    132
    Hello hotshotennis, in line 32, you need to send to function insertionSort( ) a variable of type double * in the first argument, and you are instead sending a variable of type int *. So, you must declare another variable to be sent of type double *, or you can do a type casting like this:

    Code:
    insertionSort((double *)ptr, counter);
    Also, you should not use the address operator (&) in the first argument; suppose you are sending a variable of type double * to function insertionSort, which could be ptr after the above casting, or another variable you declare to be of type double *. So, to generalize, let's call it x, and let's suppose, like I said, it is of type double *. So, it is a pointer, and, as such, it stores an address. If you do &x, you are sending the address of an address, which is of type double **, and function insertionSort( ) expects a variable of type double *. In your program, try doing the following modification before doing the right one I suggested above: declare a variable of type double *, say p, and change line 32 to

    Code:
    insertionSort(&p, counter);
    After that, try compiling the program again, and see the warning you'll get. If instead you do this:

    Code:
    insertionSort(&(double *)ptr, counter);
    you won't see the warning I'd like you to see. Also, I ran a part of your program, and when I enter -1, it doesn't finish the input. I think it has something to do with line 32 - there, you call the same function you already where in, that is, getNum( ), and I think it is a kind of loop the program is in, maybe an infinite one.

    See ya!
    Last edited by stdq; 05-12-2012 at 01:17 AM.

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Quote Originally Posted by Kazansky View Post
    Have you actually got this working before? From what I'm reading this doesn't make any sense.
    Yes, I have. Basically, most of what is now in getNum, was in main. getNum only had lines 56 - 60. Everything else was in main. But then I took it out of main and put it in getNum. And the insertionSort function is new too. But if you ignore the sort function, and put the getNum code in main, it worked fine up to that point.

  5. #5
    Registered User
    Join Date
    May 2012
    Location
    Manitoba, Canada
    Posts
    12
    As stdq said, I was logically going through the program and it just loops, at line 63 you try and get a number by calling the getNum function which you're already in, it then asks for a number and tries to get through the same function. It just loops there.

  6. #6
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Quote Originally Posted by Kazansky View Post
    As stdq said, I was logically going through the program and it just loops, at line 63 you try and get a number by calling the getNum function which you're already in, it then asks for a number and tries to get through the same function. It just loops there.
    Ok thank you both. I fixed the calling statement so that it works. But you're right, by moving my code that was in main into the getNum function, I ended up creating an infinite loop. Not sure how to fix this though. I'll try to go through my code and figure it out.

  7. #7
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    stdq gives some good advice, but I must say that type casting is not a valid option to get rid of this error, specifically because you aren't really fixing it, just sweeping it under the rug of confusion. If you intend to malloc 1000 doubles for an array, then just make a double * variable and use that. Casting makes it impossible for the compiler to check your work for type incompatibilities -- it's like saying you know better than the compiler, which is rarely the case.

    Note, the preferred idiom for malloc'ing is this (for any type, foo):
    Code:
    foo *some_var = malloc(nfoo * sizeof(*some_var));  // malloc space for nfoo objects of whatever type some_var points to
    Note how I use the variable that is storing the result of malloc in the sizeof statement. It guarantees I malloc the right amount of memory, even if you change the type of some_var, or the contents of a foo object. You do something similar in your first malloc call, but you should have used *pptr, not *ptr.

  8. #8
    Registered User
    Join Date
    May 2012
    Location
    Manitoba, Canada
    Posts
    12
    Still going through the code, on line 66 you have

    Code:
    *p_walker = number;
    This is invalid, if you want p_walker to point to the value of number it would be like:

    Code:
    p_walker = &number;
    I'm assuming that's what you want based on this line:

    Code:
     printf("entered: %lg \n", *p_walker);

  9. #9
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    //#include <crtdbg.h>  // do not remove
    
    #define FLUSH while (getchar() != '\n')
    #define MEM_ERROR printf("Not enough memory!\n")
    
    // Prototype Declarations
    double getNum(void);
    double insertionSort(double *ptr, int counter);
    
    int main (void)
    {
    double *ptr;
    double **pptr;
    int counter;
    int i;
    int number;
    double num;
    double* p_walker;
    
    
    
           //  Local Definitions
           //  Statements
           printf("\t\t Homework 3 - Pointer Applications:\n"
                      "\t\t    Insertion Sort and Pointers\n\n" );
           if(!(pptr = malloc(1000 * sizeof (*pptr)))){
                   printf("Not enough memory available.\n"); // no memory available
                   exit(100);
           }
    
           if(!(ptr = malloc(1000 * sizeof ( *ptr )))){
                   printf("Not enough memory available.\n"); // no memory available
                   exit(100);
           }
    
           printf("\nPlease enter numbers and enter -1 when you are done: ");
           number = getNum();
           p_walker = ptr;
           while(number!= -1){
                   *p_walker = number;
                   pptr[counter] = p_walker;
                   printf("entered1: %lg \n", number);
                   printf("entered: %lg \n", *p_walker);
                   number = getNum();
                   p_walker++;
                   counter++;
    
           }
                   printf("endpointer = %ld startPointer = %ld Counter = %d\n", p_walker, ptr, counter);
           ptr = realloc(ptr, counter * sizeof(double));
           if( ptr == NULL )
              MEM_ERROR;
           else
              ptr = ptr;
    
    
           for (i = 0; i < counter; i++) {
                   //printf("%lg\t",*(ptr+i));
                   printf("%lg\t", *(*pptr + i));
           }
    
           getNum();
           insertionSort(ptr, counter);
    
           //  printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n");  // do not remove
           printf("\n\t\tEnd of Program\n"
                      "\n\t\tHave a great day!\n");
    
           return 0;
    
    }
    
    /************************************************
     Prompt the user to enter a valid integer number
     Pre: nothing
     Post: returns a valid integer
    */
    double getNum(void)
    {
     double num;
           while (scanf("%lg", &num) != 1)
           {
                         // scanf returns 1 if number read corrrectly
               FLUSH;    // to "consume" the invalid input
              printf("-*- Invalid number. Please re-enter: ");
           } // while
    
    
       return num;
    }
    
    double insertionSort(double *ptr, int counter)
    {
    int i, j;
    double temp;
    
           for(i = 1; i < counter; i++)
           {
                   temp = ptr[i];
                   j = i - 1;
                           while(temp < ptr[j] && j >= 0)
                           {
                                   ptr[j + 1] = ptr[j];
                                   j = j - 1;
                           }
                   ptr[j + 1] = temp;
           }
    
           printf("\n The ascending order of the list is: \n");
           for (i = 0; i < counter; i++)
           {
                   printf("\n%d", ptr[i]);
           }
    
    
    
    }
    -@anduril462 first I was thrown off by all of the "foo" and "nfoo" lol but then I think I figured it out. I changed everything around and that seems to work. Of course, the program itself doesn't work. I tried to backtrack and return the stuff I moved back to main, but it doesn't seem to work like it used to. If someone sees some error that I don't, please let me know.

  10. #10
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Quote Originally Posted by Kazansky View Post
    Still going through the code, on line 66 you have

    Code:
    *p_walker = number;
    This is invalid, if you want p_walker to point to the value of number it would be like:

    Code:
    p_walker = &number;
    I'm assuming that's what you want based on this line:

    Code:
     printf("entered: %lg \n", *p_walker);
    This has been fixed. Thank you, its still not working properly all the way though. Doesn't seem to print correctly...

  11. #11
    Registered User
    Join Date
    May 2012
    Location
    Manitoba, Canada
    Posts
    12
    Doesn't seem to print correctly...
    What doesn't?

    Also what's going on on line 76? Are you trying to print the values or the addresses? "%ld" as you have it is for long integers, not doubles or pointers.

  12. #12
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Quote Originally Posted by Kazansky View Post
    What doesn't?

    Also what's going on on line 76? Are you trying to print the values or the addresses? "%ld" as you have it is for long integers, not doubles or pointers.
    That line is pretty much a testing line and will be removed later. When I was first writing the program I wanted to check that counter was counting correctly. Basically, the first two things printed are addresses, the starting address and ending address, and then the counter total.

    The thing that doesn't print correctly is the array after I scan in the numbers. It gives me garbage and then just sort of pauses midway through the program without ever going on to insertionSort.

    Hope that makes sense.

  13. #13
    Registered User
    Join Date
    May 2012
    Location
    Manitoba, Canada
    Posts
    12
    I'm still looking at your original code and I can see you're having trouble with variable scope. Variables created inside a function are internal to that function, when the function ends so do the variables. Numerous times such as line 32 you try passing undeclared variables. If you want to modify variables from one function in another you have to pass them as arguments, otherwise as I've said it wouldn't pass when the function exists.

  14. #14
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Quote Originally Posted by Kazansky View Post
    I'm still looking at your original code and I can see you're having trouble with variable scope. Variables created inside a function are internal to that function, when the function ends so do the variables. Numerous times such as line 32 you try passing undeclared variables. If you want to modify variables from one function in another you have to pass them as arguments, otherwise as I've said it wouldn't pass when the function exists.
    Yeah thats true. I have a hard time keeping track of this. Its something that I only recently started to worry about, and I'm not doing a very good job with it. Thank you for your continued help though.

  15. #15
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    //#include <crtdbg.h>  // do not remove
    
    #define FLUSH while (getchar() != '\n')
    #define MEM_ERROR printf("Not enough memory!\n")
    
    // Prototype Declarations
    double getNum(void);
    double insertionSort(double *ptr, int counter);
    
    int main (void)
    {
    
    //Local Definitions
    double *ptr;
    double **pptr;
    int counter;
    int i;
    
    double number;
    double* p_walker;
    
    
           //  Statements
           printf("\t\t Homework 3 - Pointer Applications:\n"
                      "\t\t    Insertion Sort and Pointers\n\n" );
           if(!(pptr = malloc(1000 * sizeof (*pptr)))){
                   printf("Not enough memory available.\n"); // no memory available
                   exit(100);
           }
    
           if(!(ptr = malloc(1000 * sizeof ( *ptr )))){
                   printf("Not enough memory available.\n"); // no memory available
                   exit(100);
           }
    
           printf("\nPlease enter numbers and enter -1 when you are done: ");
           number = getNum();
           p_walker = ptr;
           while(number!= -1){
    
                   p_walker = &number;https://mail.google.com/mail/images/cleardot.gif
    
    
    
                   pptr[counter] = p_walker;
                   printf("entered1: %lg \n", number);
                   printf("entered: %lg \n", *p_walker);
                   number = getNum();
                   p_walker++;
                   counter++;
    
           }
                   printf("endpointer = %ld startPointer = %ld Counter = %d\n", p_walker, ptr, counter);
    
    
    
    
           for (i = 0; i < counter; i++) {
                   //printf("%lg\t",*(ptr+i));
                   printf("%lg\t", *(*pptr + i));
           }
           ptr = realloc(ptr, counter * sizeof(double));
           if( ptr == NULL )
              MEM_ERROR;
           else
              ptr = ptr;
    
    
    
           insertionSort(ptr, counter);
    
           //  printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n");  // do not remove
           printf("\n\t\tEnd of Program\n"
                      "\n\t\tHave a great day!\n");
    
           return 0;
    
    }
    
    /************************************************
     Prompt the user to enter a valid integer number
     Pre: nothing
     Post: returns a valid integer
    */
    double getNum(void)
    {
     double num;
           while (scanf("%lg", &num) != 1)
           {
                         // scanf returns 1 if number read corrrectly
               FLUSH;    // to "consume" the invalid input
              printf("-*- Invalid number. Please re-enter: ");
           } // while
    
    
       return num;
    }
    
    double insertionSort(double *ptr, int counter)
    {
    int i, j;
    double temp;
    
           for(i = 1; i < counter; i++)
           {
                   temp = ptr[i];
                   j = i - 1;
                           while(temp < ptr[j] && j >= 0)
                           {
                                   ptr[j + 1] = ptr[j];
                                   j = j - 1;
                           }
                   ptr[j + 1] = temp;
           }
    
           printf("\n The ascending order of the list is: \n");
           for (i = 0; i < counter; i++)
           {
                   printf("\n%d", ptr[i]);
           }
    
    
    
    }
    

    -This is the latest version of my code. When I compile it, and enter my first number, it hits segmentation fault immediately. Its 2am over here, so I need to get to bed. Some of these dumb errors might be because I'm really tired. Not sure. Anyway, aside from fixing this mess, I would ideally like to take out that chunk of code out of main and place it into getNum. I'll check back tomorrow morning if anyone has any suggestions as to what is wrong.
    P.S. Sorry if my code is making your eyes bleed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  2. Replies: 4
    Last Post: 07-01-2009, 01:53 PM
  3. Replies: 2
    Last Post: 04-27-2008, 03:39 AM
  4. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  5. Replies: 5
    Last Post: 11-19-2002, 09:36 PM