If I declare it as:

void myFunction(int *array, ...);

Will I still be able to do:

array[position] = value;

Yes - this is legal syntax.

Also, if I am working with a dynamically allocated matrix, which one is correct to declare the function prototype:

void myFunction(int matrix[][], ...);

Or

void myFunction(int **matrix, ...);

...?

If you're working with more than one dimension, you'll have to declare the size of all but the first dimension in the function declaration, like so:

void myFunction(int matrix[][100], ...);

This syntax won't do what you think it does:

void myFunction(int **matrix, ...);
matrix[i][j] = ...

This declares a parameter named matrix that is a pointer to a pointer to int; attempting to dereference using matrix[i][j] will likely cause a segmentation fault.

This is one of the many difficulties of working with a multi-dimensional array in C.

Here is a helpful SO question addressing this topic: Define a matrix and pass it to a function in C

Answer from Tom on Stack Overflow
Top answer
1 of 4
8

If I declare it as:

void myFunction(int *array, ...);

Will I still be able to do:

array[position] = value;

Yes - this is legal syntax.

Also, if I am working with a dynamically allocated matrix, which one is correct to declare the function prototype:

void myFunction(int matrix[][], ...);

Or

void myFunction(int **matrix, ...);

...?

If you're working with more than one dimension, you'll have to declare the size of all but the first dimension in the function declaration, like so:

void myFunction(int matrix[][100], ...);

This syntax won't do what you think it does:

void myFunction(int **matrix, ...);
matrix[i][j] = ...

This declares a parameter named matrix that is a pointer to a pointer to int; attempting to dereference using matrix[i][j] will likely cause a segmentation fault.

This is one of the many difficulties of working with a multi-dimensional array in C.

Here is a helpful SO question addressing this topic: Define a matrix and pass it to a function in C

2 of 4
3

Yes, please use array[position], even if the parameter type is int *array. The alternative you gave (*array[position]) is actually invalid in this case since the [] operator takes precedence over the * operator, making it equivalent to *(array[position]) which is trying to dereference the value of a[position], not it's address.

It gets a little more complicated for multi-dimensional arrays but you can do it:

int m = 10, n = 5;

int matrixOnStack[m][n];
matrixOnStack[0][0] = 0;      // OK
matrixOnStack[m-1][n-1] = 0;  // OK
// matrixOnStack[10][5] = 0;  // Not OK. Compiler may not complain
                              // but nearby data structures might.

int (*matrixInHeap)[n] = malloc(sizeof(int[m][n]));
matrixInHeap[0][0] = 0;       // OK
matrixInHeap[m-1][n-1] = 0;   // OK
// matrixInHeap[10][5] = 0;   // Not OK. coloring outside the lines again.

The way the matrixInHeap declaration should be interpreted is that the 'thing' pointed to by matrixInHeap is an array of n int values, so sizeof(*matrixInHeap) == n * sizeof(int), or the size of an entire row in the matrix. matrixInHeap[2][4] works because matrixInHeap[2] is advancing the address matrixInHeap by 2 * sizeof(*matrixInHeap), which skips two full rows of n integers, resulting in the address of the 3rd row, and then the final [4] selects the fifth element from the third row. (remember that array indices start at 0 and not 1)

You can use the same type when pointing to normal multidimensional c-arrays, (assuming you already know the size):

int (*matrixPointer)[n] = matrixOnStack || matrixInHeap;

Now lets say you want to have a function that takes one of these variably sized matrices as a parameter. When the variables were declared earlier the type had some information about the size (both dimensions in the stack example, and the last dimension n in the heap example). So the parameter type in the function definition is going to need that n value, which we can actually do, as long as we include it as a separate parameter, defining the function like this:

void fillWithZeros(int m, int n, int (*matrix)[n]) {
    for (int i = 0; i < m; ++i)
        for (int j = 0; j < n; ++j)
            matrix[i][j] = 0;
}

If we don't need the m value inside the function, we could leave it out entirely, just as long as we keep n:

bool isZeroAtLocation(int n, int (*matrix)[n], int i, int j) {
    return matrix[i][j] == 0;
}

And then we just include the size when calling the functions:

fillWithZeros(m, n, matrixPointer);
assert(isZeroAtLocation(n, matrixPointer, 0, 0));

It may feel a little like we're doing the compilers work for it, especially in cases where we don't use n inside the function body at all (or only as a parameter to similar functions), but at least it works.

One last point regarding readability: using malloc(sizeof(int[len])) is equivalent to malloc(len * sizeof(int)) (and anybody who tells you otherwise doesn't understand structure padding in c) but the first way of writing it makes it obvious to the reader that we are talking about an array. The same goes for malloc(sizeof(int[m][n])) and malloc(m * n * sizeof(int)).

Top answer
1 of 2
1

In C, everything is passed by value. In your concrete example arr is. You don't have references like in C++ or Java.

Let's take a C++ example:

void foo(int& i) {
    ++i;
}

int main() {
    int i = 1;

    foo();
}

Here, true references are used. i is passed by reference and foo modifies i over a reference to i. No "copying by value" takes place.

OTOH, in C, you don't have references. You can only write something like

void foo(int* i) {
    ++*i;
}

int main() {
    int i = 1;

    foo(&i);
}

To pass something "by reference"1 in C, you need to pass a pointer to it, just like you did. The pointer itsself is passed by value but it refers to a memory area (here i) modifiable by both the function and the allocator.

In the end, if you want to pass something "by reference" in C, copying by value is always involved. Not so in C++.

Quoting from K&R, 1.8 Arguments - Call by Value:

In C, all function arguments are passed by value.''


1 Note that this is within double quotes. C doesn't have "pass-by-reference." Period.

2 of 2
1

It is "both":

The pointer is passed by value, the array "by reference".

C Standard draft, N1256:

6.5.2.2 Function calls
...
4 An argument may be an expression of any object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.
...

I put "both" and "by reference" in quotes, because there are no references in C. A pointer is not a reference, but when used to "pass an array" to a function, it is roughly comparable, in the sense that if the function modifies the array, the changes are visible to the caller. I think this helps understanding what happens here.
We say that an array decays to a pointer, when passed to a function. "Decay" because the pointer looses some information, namely the length of the array. So saying this is similar to "pass by reference" is meant only from an application point of view.

Discussions

c - How to pass a 2D dynamically allocated array to a function? - Stack Overflow
I have a 2 dimensional array dynamically allocated in my C code, in my function main. I need to pass this 2D array to a function. Since the columns and rows of the array are run time variables, I k... More on stackoverflow.com
🌐 stackoverflow.com
c - Passing a dynamically allocated array from main to another function - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I am trying to pass a dynamically allocated array as a parameter to another function. More on stackoverflow.com
🌐 stackoverflow.com
Passing two different dynamically allocated arrays to function in C - Stack Overflow
I've no idea whether that's an ... such change is accidental and unintentional). The types of the function matrix parameters are modified to be simpler to manage, and the memory allocation is assigned to an appropriate pointer to an array of double values. Note that for a 6x6 array, using dynamic memory allocation ... More on stackoverflow.com
🌐 stackoverflow.com
Dynamically allocated arrays and why they need to be passed by reference to be used in a function / pointer review
you are mixing c with cpp, your styling is c-like and mingling with reference concept(cpp). you are using reference because you know something has to be changed within the resize function. int* reSize(int& siZe, int*& oldPtr) took reference from siZe is right, but oldPtr isn't changed so the measure isn't necessary and in an awkward way. in C styling if an array's allocation should be changed, we use like //using double pointer to change the underlying address. void allocate(char** ptr, int size) { *ptr = malloc(size) memset(*ptr, '\0', size); } //---------------------------------- char* buffer = NULL; allocate(&buffer, 64); the double pointers mechanism is something like your doing. the pointer itself is to be changed in a function. but since modern cpp doesn't do it anymore, you should use a much sophisticated way to do these. instead of a legacy coding, isolate the raw pointer operation into a separated class to manage underlying resources. class myVec { public: myVec() { //initializing } ~myVec() { //cleanup resources } void resize(int nSize) { //don't forget to free the old pointer } //expose visible variables int GetSize(); int* GetAddress(); private: int size = 5; int* arr = nullptr; }; //use a dedicated class to deal with datas class IterArr { public: static void print(const myVec&) { //print the values } }; More on reddit.com
🌐 r/cpp_questions
15
0
October 1, 2024
🌐
Stack Overflow
stackoverflow.com › questions › 70594026 › pass-a-dynamically-allocated-array-by-value-to-function-in-c
Pass a dynamically allocated array by value to function in c - Stack Overflow
Dynamically allocate an array. Pass array by value to function. Within the function, convert string values, do calculations, sort based on calculations.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › how-arrays-are-passed-to-functions-in-cc
Pass Array to Functions in C - GeeksforGeeks
July 23, 2025 - Instead of using array notation arr[] in the function parameter, we can directly use pointer notation int *arr. All are equivalent, as arrays in C are treated as pointers to the first element of the array.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 161453-passing-dynamically-allocated-structure-array-function.html
Passing dynamically allocated structure array to function
By flawed, I think he means bad logic, misunderstanding of how memory allocation works, failure to actually allocate all the memory you need (you have n students in the array, and each of those needs it's own malloc. You can assign the result of malloc directly to s[i] (hint, you must do this repeatedly, for each i up to number of students) and use scanf to read values directly into &s[i]->score or whatever the descriptive name you pick for the struct members is. You also should pick better names for your struct members and functions, and not use all caps (that is conventionally used for macros and constants).
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 47212441 › passing-two-different-dynamically-allocated-arrays-to-function-in-c
Passing two different dynamically allocated arrays to function in C - Stack Overflow
I've no idea whether that's an appropriate calculation or not, but that isn't changed from the code in the question AFAICT (any such change is accidental and unintentional). The types of the function matrix parameters are modified to be simpler to manage, and the memory allocation is assigned to an appropriate pointer to an array of double values. Note that for a 6x6 array, using dynamic memory allocation is really not necessary; ordinary allocation on the stack would work fine.
🌐
Swarthmore College
cs.swarthmore.edu › ~newhall › unixhelp › C_arrays.html
Arrays in C
Dynamically allocated arrays are allocated on the heap at run time. The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket). To dynamically allocate space, use calls to malloc passing in the total number ...
🌐
Codefinity
codefinity.com › courses › v2 › b7943689-5d01-4a22-a024-0d29968dd8ac › 1a501801-d88a-4518-b0cb-f884c8ab1704 › 5cb0482a-5807-4011-9ca0-2df7f953d534
Learn Passing Dynamic Array as an Argument of the Function | Function Arguments Specification
Since arrays decay into pointers when passed to functions, you can pass a pointer to the first element of the array. Here's how you can do it: ... 12345678910111213141516171819202122232425262728 #include <iostream> // Function that takes a dynamic ...
🌐
Reddit
reddit.com › r/cpp_questions › dynamically allocated arrays and why they need to be passed by reference to be used in a function / pointer review
r/cpp_questions on Reddit: Dynamically allocated arrays and why they need to be passed by reference to be used in a function / pointer review
October 1, 2024 -

NOTE: This is about an EXAM THAT HAS ALREADY HAPPENED THERE IS NO CHEATING INVOLVED

Hello everyone I hope this post finds you all well. I had an exam today for one of my computer science classes 20% of the exam grade is just explaining your code, I was able to complete the prompt to the best of my ability but I could not explain for the life of me why I passed by reference a dynamically allocated array (I just knew it was something I had to do and I did it off instinct) And I wanted a deeper explanation on if we were to use a dynamically allocated array as a parameter for a function why would we need to pass it by reference. Along with I wanted to know any odd quirks that pointers have in relation to their syntax. I'm going to put my code, the outputs from it, and the prompt in a google doc below (note the prompt is at the bottom of the doc)

Top answer
1 of 5
5
you are mixing c with cpp, your styling is c-like and mingling with reference concept(cpp). you are using reference because you know something has to be changed within the resize function. int* reSize(int& siZe, int*& oldPtr) took reference from siZe is right, but oldPtr isn't changed so the measure isn't necessary and in an awkward way. in C styling if an array's allocation should be changed, we use like //using double pointer to change the underlying address. void allocate(char** ptr, int size) { *ptr = malloc(size) memset(*ptr, '\0', size); } //---------------------------------- char* buffer = NULL; allocate(&buffer, 64); the double pointers mechanism is something like your doing. the pointer itself is to be changed in a function. but since modern cpp doesn't do it anymore, you should use a much sophisticated way to do these. instead of a legacy coding, isolate the raw pointer operation into a separated class to manage underlying resources. class myVec { public: myVec() { //initializing } ~myVec() { //cleanup resources } void resize(int nSize) { //don't forget to free the old pointer } //expose visible variables int GetSize(); int* GetAddress(); private: int size = 5; int* arr = nullptr; }; //use a dedicated class to deal with datas class IterArr { public: static void print(const myVec&) { //print the values } };
2 of 5
3
So we're talking about this: int *reSize(int &siZe, int *&oldPtr); Why pass a reference to a pointer? Frankly, you shouldn't. Not here. By passing a non-const reference, you're suggesting you're going to modify oldPtr as an out-parameter. Like this: void reSize(int &siZe, int *&oldPtr) { for(int i = 0; i < siZe; i++){ cout << *(oldPtr + i)<<" "; } cout << endl <<"Enter the new size of the bootleg vector" << endl; int newSize; cin >> newSize; int* newptr = new int[newSize]; for(int i = 0; i < siZe; i++){ *(newptr + i) = *(oldPtr + i); } siZe = newSize; oldPtr = newptr; } Notice how I have changed the return type to void, and the last statements reassigns the newPtr to the oldPtr. Looking at your original use case, you were calling this function like so: bootleg_vector = reSize(siZe, bootleg_vector); With my changes, you could write: reSize(siZe, bootleg_vector); And this would have the same effect. Out-parameters are a C idiom, and are discouraged. You did it right that you're returning a value, but that means your reference to the pointer is unnecessary, misleading, error prone, and maybe even a little redundant. In C, a pointer is a "reference", according to their lingo. In C++, a pointer is a "handle" and a reference is an "alias". In other words, you made oldPtr to be booleg_vector exactly - these aren't separate variables - one in main and another as a function parameter on the call stack, oldPtr IS bootleg_vector, just with another name. Remember that a pointer is just another variable type that stores a memory address as it's value. Pointers are variables, they take up space, they have their own memory address. The code you wrote is exactly the same as the first parameter - int &siZe, if you change siZe, you actually change the siZe variable you have declared inside main. You don't have to or want to pass everything by reference all the time. Often times the compiler will reduce your reference to a pointer under the hood, if it can't generate a proper alias. So you're not saving space or increasing speed, you're adding the cost of an indirection. Primitive types are so small that if you're going to use them in a read-only fashion, you can pass them by value. Your function signature ought to be: int *reSize(int siZe, int *oldPtr); If it helps, us a TYPE alias: using int_ptr = int*; int_ptr reSize(int siZe, int_ptr oldPtr);
🌐
Stack Overflow
stackoverflow.com › questions › 74584006 › how-to-pass-array-to-function-and-realloc-memory-in-c
How to pass array to function and realloc memory in C - Stack Overflow
Just like any other variable, if you want it to change from another function, you have to pass it's address as argument, if you want to change a pointer, send the address of the pointer (pointer to pointer) to the function.
🌐
Solarian Programmer
solarianprogrammer.com › 2019 › 03 › 27 › c-programming-passing-multi-dimensional-array-to-function
C Programming - Passing a multi-dimensional array to a function | Solarian Programmer
March 27, 2019 - In order to allocate memory for the above array we need to first allocate memory for the row pointers and next allocate memory for each row in a loop. Here is a possible implementation: 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void print_2d_array_of_pointers(int rows, int cols, int **a) ...
🌐
Scaler
scaler.com › home › topics › pass array to function in c
Passing Array to Function in C - Scaler Topics
April 25, 2024 - For first three cases we can return the array by returning poiniter pointing to base address of the array. Dynamically create an array inside the function and then return a pointer to the base address of this array.
🌐
Programiz
programiz.com › c-programming › c-arrays-functions
Pass arrays to a function in C
In this tutorial, you'll learn to pass arrays (both one-dimensional and two-dimensional arrays) to a function in C programming with the help of examples.
🌐
Stack Overflow
stackoverflow.com › questions › 894604 › passing-dynamically-allocated-integer-arrays-in-c
Passing dynamically allocated integer arrays in C - Stack Overflow
*/ int *ints = NULL; size_t i = 0; /* Pass *the addresses* of the chars and ints arrays, so that they can be * initialized. */ make(&chars, &ints, ELEMENTS); for (i = 0; i < ELEMENTS; ++i) { printf("%s and %d\n", chars[i], ints[i]); /* Don't ...