So if I get it correctly, it it did not make sense to return field, because Im changing the variable at the memory location now? And I can acces it globally by refering at the beginning in a function? |
Uh, sorry, I'm not sure of what you're saying here
I still find it a bit vague how you get 2 dimensions by reffering a pointer to a pointer. |
Pointers can be pretty hard to deal with at the beginning.
I'll assume you're familiar with the similarity of pointers and arrays. Since an array is a sequence, it can be represented like this
1D array
[0][ ][ ][ ]
Since we're talking about a pointer to pointers, it's the same as saying an array of arrays. So we can represent it like this
2D array
[0][ ][ ][ ]
[0][ ][ ][ ]
[0][ ][ ][ ]
[0][ ][ ][ ]
The computer won't actually store the data in this way, but the mechanism with which we access it can be represented with a matrix. And here's your two dimensions. The key is to remember that pointers and arrays both do the same thing: hold the address of a chunk of data
-------------------------------------------------------------
About your code, there are several new problems:
In create_field() you're creating 'field' which is [a variable] local to the function. This means that when the functions ends 'field' gets deleted (every local variable is) and you can't access it in print_field()
In print_field() you are again creating a 'field' which is not the one you previously populated
Moreover, a difference between pointers and arrays is that when you create an array the memory to store its elements is automatically reserved.
To do that with pointers you need to use dynamic memory allocation, which you are not. So your 'field**' doesn't actually point to any valid memory location. In your loops you try to access those location and that makes your program crash ("segmentation fault" if you want to google it)
So, unless you want to study how 'new' works, you better define 'field' as
char[x][y]
. The type will be the same (char** == char[][]) but giving the size in the brackets will reserve valid memory.
Now, to make 'field' accessible to both functions you have two options: make it a global variable (bad, don't do this unless your life is threatened) or create it in main() and pass it as argument to both functions