Passing Array List pointer to function

I'm going to pass my array pointer to the function parameter. I'm quite not sure how to use pointer as array list. Here my current codes...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void FunctionA(int arr_merge[])
{
    int SizeArray = sizeof(arr_merge)/sizeof(arr_merge[0]);
    cout << SizeArray << endl; //Output 0 instead of 9
    int BeginIndex = 0;
    int LastIndex = arr_merge[SizeArray-1];
    int mid = floor(BeginIndex+LastIndex/2);
}

int main (void)
{
    int arrayNumber[] = {1,2,3,4,5,6,7,8,9};
    FunctionA(arrayNumber);
    return 0;
}
Last edited on


To assign the variable LastIndex to the last element of the array,arr_merge[SizeArray] is enough. Subtracting one from the subscript gives the second to last element.

To find the middle of an array you need parenthesis.

((BeginIndex+LastIndex)/2)

Not sure why thats a parameter when it can just be assigned to mid though.

Arrays are implicitly passed as pointers automatically...I think that's what you were trying to know....
Last edited on
closed account (z05DSL3A)
In reality void FunctionA(int arr_merge[]) is void FunctionA(int * arr_merge). So inside the function you have no information about the size of the array, so SizeArray is being calculated as the size of a pointer divided by the size of an int (I would expect that to be one but anyway).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// either pass in the size...
void FunctionA(int arr_merge[], int N)
{
    int SizeArray = N;
    cout << SizeArray << endl; 
}

//or pass the array by reference, and use templates
template <typename T, int N>
void FunctionB(T (&arr_merge) [N])
{
    int SizeArray = N;
    cout << SizeArray << endl; 
}


int main()
{
    int arrayNumber[] = {1,2,3,4,5,6,7,8,9};
    
    // pass in the size
    int size = (sizeof(arrayNumber)/sizeof(arrayNumber[0]));
    
    FunctionA(arrayNumber, size);
    
    // pass the array by reference...
    FunctionB(arrayNumber);

    return 0;
}
Last edited on by Canis lupus
Topic archived. No new replies allowed.