Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass an array inside an array to a function in C?

Here’s the code that shows the basic idea of what I’m trying to do:

#include <stdio.h>

void thisFunc(int arr){
  int firstValofBob = arr[0][0];
  int secondValofBob = arr[0][1];
}
 
int main()
{
  int bob[2] = {12, 13};
  int jim[2] = {20, 50};
  int arr[2] = {bob, jim};

  thisFunc(arr);
}

I’d like to pass an array (arr[]) which contains multiple arrays itself (bob[] and jim[]) to a function, so that I can access the values inside bob[] and jim[].

I know the code here will not work, and that I probably need to use pointers in some way. Suggestions for a good way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To store the values of both bob and jim, you need to create an array that stores array of integers and then pass it to the function. My implementation is:

#include <stdio.h>

void thisFunc(int** arr){
    int firstValofBob = arr[0][0];
    int secondValofBob = arr[0][1];
}

int main()
{
    int bob[2] = {12, 13};
    int jim[2] = {20, 50};
    int* arr[2] = {bob, jim};

    thisFunc(arr);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading