Passing variables between functions

hey everyone,
I am trying to create two functions
1)sets a 2d dynamic arrays full of certain characters
2) return the character in the row and column input

something like

void setmatrix()
{
char matrix = new char[*11];
// code
};
char getelement(int r, int c)
{ return(matrix[r][c]);
}

I have no problem with creating functions and declaring arrays; I just can't figure out how to allow a function to just return the variable (in this cases one element of the array) of another function.

Thanks
Last edited on
you have to pass everything you want to interact with.
eg

void setmatrix(char *& matrix)
{
matrix = new ...
}

char getelement(char** matrix, int r, int c)
{
return matrix[r][c]; // this is more work than just typing matrix[r][c] back where you called it, though.
}

this is where object oriented programming has merits. the class has the matrix and your methods can interact with it as if it were a global, without all the passing around.

by the way, as you have it, matrix is lost when the function ends, leaking its memory. You must keep a handle on your pointers and not lose them this way. The calling function needs to have that pointer so it can destroy it later (and use it for something, of course).
Last edited on
@jonnin
Thank you so much for replying
I always use classes but that specific assignment asks that I use functions I don't know why.
what if my matrix wasn't passed from the main in the first place? (it was declared and used in the function setmatrix; the other function receives a row (r) and column(c) from the main and prints the item in this specific row and column)
Last edited on
you need a way to get to it. setmatrix needs to either accept it as a reference parameter or return it.
there are other hacky ways around doing it right, but surely that isn't what they want. You can do it with a global, of course, or other uglies.
Last edited on
I'll recheck with them
Thank you again
Topic archived. No new replies allowed.