1

I initialized a 2D int array in my main function with int weight[numComponents][numSchemes]; Now I would like to pass it on to a function to add items to it.

I was wondering what the correct way to do this is. I came across this answer C -- passing a 2d array as a function argument?

But it seems like the array gets initialized in the function itself instead of beforehand. If anyone could help, that would be great. Just looking to be able to pull some statements like weight[0][0] = 50; weight[0][3] = 20;

Community
  • 1
  • 1

1 Answers1

1

A simple example for passing a 2D array as a function argument:


#include <stdio.h>

void weightInput(int numComponents, int numSchemes, int weight[][numSchemes])
{
    weight[0][0] = 50;
    weight[0][3] = 20;
}
int main() 
{
    int numComponents = 3, numSchemes = 4;
    int weight[numComponents][numSchemes];
    weightInput(numComponents, numSchemes, weight);
    printf("%d\n", weight[0][0]);
    printf("%d\n", weight[0][3]);
}
ani627
  • 5,578
  • 8
  • 39
  • 45