0

I thought of doing

int arr[row][col];

But I guess since I am to pass the entire arr to a function multiple number of times, hence it may give me stackoverflow [since ROW and COL can be a few thousands]. Hence if I do it using pointers instead then passing on the pointer would be a better way , since I also intend to change the values of the array as it passes through various functions.

How do I define the array using pointer and how do I pass it to the function? Intend to do arr[i][j] whenever I want to access an element.

1
  • possible duplicate of passing 2D array to function Commented Jul 12, 2013 at 12:03

2 Answers 2

3

When you pass arrays around as arguments, you only pass a pointer to its first element, not the entire array.

So the function signature could look something like this:

void some_function(int arr[][col]);

Or optionally

void some_function(int (*arr)[col]);

If the column size is not a global compile-time constant, then you can pass it as argument to the function as well:

void some_function(const size_t col, int arr[][col]);

Or

void some_function(const size_t col, int (*arr)[col]);
Sign up to request clarification or add additional context in comments.

11 Comments

This will just put the arr pointer on the stack with the message call and not the entire array?
OP wants to change values of array through various functions too.So i guess it should be pointer to pointer rather than just pointer.
@Kraken That's right, arrays decays to pointers when passed around, so only pointers will be passed not the complete (or parts of the ) array.
@Dayalrai A pointer to pointer and an array or arrays (or a pointer to an array) are two very different things and are not compatible. See e.g. this answer of mine for why.
@JoachimPileborg If I do this void hello(int arr[ROW][COLUMN]) and to this array I pass hello(arr) where arr is an array of size 10000*10000. Still just the pointer is copied?
|
0

Passing the array to a function is OK. Arrays are treated like pointers when passing as argument, that is, only the address of the first element is copied.

But be sure to pass number of rows and columns as arguments too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.