I'm trying to understand pointers in C and I think I have an okay grasp so far. I am trying to make sense of arrays and how they are passed to functions. It is my understanding that when passing an array to a function it is passed by reference and that when passing an array to a function it points to the beginning of the array in memory or the first memory address of the array. So if I create an array like so:
char* arr[2] = {"Andrew", "Schools"};
I could define the following functions to accept this array which is really passing a pointer to the first item in the array:
void readSingleArray(char* arr[], int count) {
for(int i=0; i<count; i++) {
printf("%s\n", arr[i]);
}
}
void readSingleArray2(char** arr, int count) {
for(int i=0; i<count; i++) {
printf("%s\n", arr[i]);
}
}
The second function accepts char** arr
instead of char* []
. So I understand this as such: since I have an array of pointers, this is telling the compiler that I want to access a pointer to a char so either way will work.
Now if I define a multi-dimensional array like so:
char* arr2[2][2] = {{"Andrew", "Schools"},{"Computer", "Programmer"}};
I can define the following function:
void readMultiDimArray(char* arr[2][2], int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}
But not this function:
void readMultiDimArray2(char** arr, int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}
I read that multi-dimensional arrays are actually single dimensional arrays or one single block of memory and the compiler will figure out how to access the appropriate array items: How to pass a multidimensional array to a function in C and C++. This makes sense to me so my question is: Why can I use a char** arr
for single arrays but when using multi-dimensional array this won't work. Because how I see it, no matter what, I only need to access the first memory address of the array since it's always going to be one continuous block of bits