1

I'm trying to write a function that manipulates an array directly.I don't want to return anything, so obviously I'm going to be using pointers in some fashion.

void makeGraph(some parameter) {
    //manipulates array
}

int main() {
    char graph[40][60];
    makeGraph(????)

}

I can't figure out what to pass in as parameters. Any help would be appreciated.

namarino
  • 113
  • 1
  • 13
  • 2
    You can pass the array directly: `void makeGraph(char graph[][60]) {` note that you don't need to specify the first dimension, call it using `makeGraph(graph)` – David Ranieri Nov 05 '16 at 06:30
  • Are dimensions fixed at compile time (so you can for example use *#define* for them)? – hyde Nov 05 '16 at 06:32
  • Yeah they're fixed. I do a #define and then some computation with them. – namarino Nov 05 '16 at 06:38
  • @keineLust why do I need to specify the size? And why don't I need to specify the size of the first array? – namarino Nov 05 '16 at 06:38
  • `void makeGraph(int rows, int cols, char graph[rows][cols])`, `makeGraph(40, 60, graph)` – BLUEPIXY Nov 05 '16 at 07:11

3 Answers3

4

I'm trying to write a function that manipulates an array directly.I don't want to return anything, so obviously I'm going to be using pointers in some fashion.

In C when you pass array automatically the base address of the array is stored by the formal parameter of the called function(here, makeGraph()) so any changes done to the formal parameter also effects the actual parameter of the calling function(in your case main()).

So you can do this way:

void makeGraph(char graph[][60])
{
    //body of the function...
}

int main(void)
{
     //in main you can call it this way:
     char graph[40][60];
     makeGraph(graph)
}

There are even other ways you can pass an array in C. Have a look at this post: Correct way of passing 2 dimensional array into a function

Community
  • 1
  • 1
Cherubim
  • 4,907
  • 3
  • 18
  • 35
2

In C array can be passed as a pointer to its first element. The function prototype could be any of these

void makeGraph(char graph[40][60]);
void makeGraph(char graph[][60]);
void makeGraph(char (*graph)[60]);  

To call this function you can pass argument as

makeGraph(graph);  //or
makeGraph(&graph[0]);    
haccks
  • 100,941
  • 24
  • 163
  • 252
2
void makeGraph(char graph[40][60]                 
{  // access array elements as graph[x][y] x and y are any number with in the array size 
 }

 int main(void) 
{ //in main you can call it this way: 
 char graph[40][60];  

 makeGraph(graph) 

}