Passing single dimensional arrays via functions

We pass a single dimensional array like this :

1
2
3
4
5
6
7
void func() // some function
      {
         int ARR[20];
         .....
         func1(ARR); // Passing the address of the first element of the array
         .....
      }


I am also aware that there are three ways to receive arrays

void func1(int *A) //Receive the address via a pointer variable
or
void func1(int A[]) //Receive the address with an unsized array
or
void func1(int A[20]) //Receive the address with an array of a size

My question is that what is the difference between the three allowed types of array receiving ? I think that changes made via a pointer variable are permanent while in the case of others it's not but I'm not sure about this. Is it true or not ? Thanks ! ^_^
All three are completely equivalent. The type of A in func1 is int*.
Last edited on
I'm aware that all the three are equivalent for receiving arrays.

Assume that the value of ARR[5] was 5 in the function func(). After that i passed the array to func1(). But if i try to access the array by doing *(A+5)=10 this will it affect the original array ARR[20] ? If yes then will the change also happen when i use A[] or A[20] ?
The the original array will be affected because A is just a pointer to the first element in the array.
Yeah, their all the same... why couldn't you test it yourself? it took me 3 minutes and you already had your editor open.

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
31
32
33
34
35
36
37
#include <iostream>

void func1(int *Array)
{
    for (int i = 0; i < 5; i++)
    {
        std::cout << Array[i] << std::endl;
        Array[i] = i*2;
    }
}

void func2(int Array[])
{
    for (int i = 0; i < 5; i++)
    {
        std::cout << Array[i] << std::endl;
        Array[i] = i*3;
    }
}

void func3(int Array[5])
{
    for (int i = 0; i < 5; i++)
    {
        std::cout << Array[i] << std::endl;
        Array[i] = i*4;
    }
}

int main()
{
    int Array[5] = {0, 1, 2, 3, 4};
    func1(Array); //replace func1 with func2 or func3
    
    for (int i = 0; i < 5; i++)
        std::cout << Array[i] << std::endl;
}
Last edited on
@Zephilinox: Thanks for that code and yeah I'm sorry. I'm just starting to learn and sought for advice before starting my project. I saw that in all the cases the original array is modified. I didn't think it would happen in the case of func2() and func()3 though. Thanks again !! :)
no problem, good luck
Topic archived. No new replies allowed.