-3

I'm having a few problems to understandU/implement something small with pointers in c. I'm having a 4x4 matrix and i want to transpose it. Its implementation is already working. but know i want to but the logic into methods to make it more fancy.

char arr[4][4] = { //filled } 
printArray(arr)

The first code part only prints the array as i formated it and its working perfectly.

char matrixTranspose(char array[4][4]) {

  char new_array[4][4];

  // logic

  return new_array;
}

So know I want to get back the the transposed matrix but I'm always getting back the warnings:

warning: function returns address of local variable [-Wreturn-local-addr]

warning: return makes integer from pointer without a cast [enabledby default]

the further steps in my main method would be to just print the new array like:

char new_matrix = matrixTranspose(arr);
printArray(new_matrix);

which results to the error:

warning: passing argument 1 of 'printArray' makes pointer from integer

without a cast [enabled by default] note: expected 'char (*)[4]' but argument is of type 'char'

So my question is, why does it have to be a pointer and when do i use the pointer ? I jsut want to overgive the variable the whole way, transpose it give it back and print it, do i need pointes? thanks for any help.

vicR
  • 789
  • 4
  • 23
  • 52
  • 4
    [returning a local variable from function in C](http://stackoverflow.com/questions/4824342/returning-a-local-variable-from-function-in-c) – P.P Nov 09 '16 at 12:19
  • 1
    Inside your function, `char new_array[4][4];` declares an array on the stack. This data is lost as soon as your function returns. I suggest you use `malloc()` to create an array on the heap and return a pointer to that instead. – r3mainer Nov 09 '16 at 12:19
  • 1
    That function is nonsense. When programming, you actually have to know what you are doing. You can't just guess with trial & error. How about reading the chapters about arrays and pointers in your C book instead? I'm sure there will be examples. – Lundin Nov 09 '16 at 12:23
  • @P.P. That problem is not just the local variable, but that the OP doesn't even understand what arrays are nor how they work. – Lundin Nov 09 '16 at 12:25
  • @Lundin That's just a related link. Not sure why felt you need to ping me on that. – P.P Nov 09 '16 at 12:26
  • @P.P. Because people are now close-voting this as a duplicate to that link. – Lundin Nov 09 '16 at 12:26
  • And C does not support _methods_, only _functions_! – too honest for this site Nov 09 '16 at 12:36

1 Answers1

2

A function should not return a non-static array declared inside it.


Change your main code to:

char arr1[4][4] = {...};
char arr2[4][4];

matrixTranspose(arr1,arr2);
printArray(arr1);
printArray(arr2);

And your function to:

void matrixTranspose(const char input_arr[4][4],char output_arr[4][4])
{
    // logic
}
barak manos
  • 29,648
  • 10
  • 62
  • 114