You could return a pointer to static variable:
char (*modify(char input))[3]
{
static char variable[3][3];
variable[0][0] = input;
variable[1][1] = input+1;
return variable;
}
int main() {
char (*result)[3] = modify(a);
}
However, this is not a reentrant function. Another option is using dynamic memory (i.e. malloc), but memory leaks are quite common when returning pointers to allocated memory.
Another approach it's to pass the array to the function, already allocated, so you don't have to be worried about releasing memory or using statics:
void modify(char variable[][3], char input) {
variable[0][0] = input;
variable[1][1] = input+1;
}
int main(void) {
char result[3][3];
modify(result,a);
}
A better approach it's to create a typedef to highlight the purpose, length and making easier working with it:
typedef struct { char x[3][3]; } my2D_t;
void modify(my2D_t *variable, char input) {
variable->x[0][0] = input;
variable->x[1][1] = input+1;
}
int main() {
my2D_t result;
char a = 1;
modify(&result,a);
}
Also returning by value as tstanisl noticed. It creates another my2D_t
, but the compiler will probably end up with something similar to the previous idea for the sake of optimization known as the "as-if" rule:
typedef struct { char x[3][3]; } my2D_t;
my2D_t modify(char input) {
my2D_t variable;
variable.x[0][0] = input;
variable.x[1][1] = input+1;
return variable;
}
int main() {
char a = 1;
my2D_t result = modify(a);
}