Thread: Dynamic array from Function to Function

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Your compiler has to be warning you about an invalid call to ArrayScan() (if it's not, it's broken, and you should get a new compiler).

    You're passing &array to ArrayScan(). array has type int*, so &array has type int**. However, ArrayScan() expects an int*. int** and int* are incompatible types.

    Passing &array is right, because you need ArrayScan() to modify array (you need it to make array point somewhere). But that means that ArrayScan() needs to take int** instead of int*; and each time you use "h" in the function, you should be using "*h". Since h points to an int*, *h is an int*, which is to say *h is the same thing as "array" in your main function.

    This is no different than passing, say, an int* to a function when it needs to modify the int. Instead, you're just passing an int** so the function can modify the int*.

  2. #2
    Registered User
    Join Date
    Oct 2014
    Posts
    2
    Thank you very much for the response, cas. I tried to change my code (wrote int **, instead of int *, changed to *h in functions). However, it doesn't compile me.
    What am i doing wrong now?
    Code:
    #include <stdio.h>#include <stdlib.h>
    void ArrayScan(int n, int **h);
    void ArrayMaximum(int n, int *h, int x);
    int main()
    {
        int n, *array;
        int max = 0;
    
    
    
    
        printf("Write the number of random numbers: ");
        scanf("%d", &n);
        ArrayScan(n,&array);
        ArrayMaximum(n,array, max);
        free(array);
        getch();
    }
    void ArrayScan(int n, int **h)
    {
     int i = 0;
     h = (int*)malloc(n* sizeof(int));
     for ( ; i<n; i++)
     scanf("%d", *(h+i));
    }
    void ArrayMaximum(int n, int *h, int x)
    {
     int i=0;
     x = *(h+i);
     for( ;i<n;i++)
     {
      if (*(h+i)>x)
      x = *(h+i);
     };
     printf("The maximum is: %d", x);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic 2D array to function
    By MaynardJ222 in forum C Programming
    Replies: 7
    Last Post: 07-15-2013, 11:48 AM
  2. Passing a dynamic array to a function
    By esmeco in forum C Programming
    Replies: 15
    Last Post: 06-05-2010, 04:25 PM
  3. passing dynamic array to function
    By rocketman03 in forum C++ Programming
    Replies: 4
    Last Post: 10-24-2009, 08:24 AM
  4. Help Returning a new Dynamic Array from a Function
    By KeithS in forum C++ Programming
    Replies: 6
    Last Post: 10-01-2009, 12:29 PM
  5. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 02:04 AM