Reputation: 519
Could anybody please tell me why is the output of both the prints are not same? How to pass an array of strings to a function then?
main()
{
char b[10][10];
printf("%p, %p, %p\n", b, b[0], b[9]);
getStrListFromString(b);
}
void getStrListFromString(char **strList)
{
printf("%p, %p, %p\n", strList, strList[0], strList[9]);
}
Expected OUTPUT :
0x7fffbe4ecf00, 0x7fffbe4ecf00, 0x7fffbe4ecf5a
0x7fffbe4ecf00, 0x7fffbe4ecf00, 0x7fffbe4ecf5a
Actual Output :
0x7fffbe4ecf00, 0x7fffbe4ecf00, 0x7fffbe4ecf5a
0x7fffbe4ecf00, 0x7fffbe4ecf80, (nil)
Upvotes: 2
Views: 122
Reputation: 213678
In addition to the core issue about pointer-to-pointer having absolutely nothing to do with multi-dimensional arrays, your also has various other bugs:
main() // obsolete form of main(), won't compile unless C90
{
char b[10][10]; // uninitialized
printf("%p, %p, %p\n", b, b[0], b[9]); // should be void pointers
getStrListFromString(b); // wrong type of parameter
// return statement necessary here in C90
}
void getStrListFromString(char **strList) // should not be pointer-to-pointer
{
printf("%p, %p, %p\n", strList, strList[0], strList[9]); // same issue as in main
}
The fact that this code compiled means that your compiler is either complete crap or incorrectly configured. You need to fix that asap.
Corrected code:
#include <stdio.h>
void getStrListFromString(char strList[10][10])
{
printf("%p, %p, %p\n", (void*)strList, (void*)strList[0], (void*)strList[9]);
}
int main (void)
{
char b[10][10];
printf("%p, %p, %p\n", (void*)b, (void*)b[0], (void*)b[9]);
getStrListFromString(b);
}
Upvotes: 2
Reputation: 223739
Your function expects a char **
but you're passing it a char [10][10]
. These are not the same.
An array when passed to a function decayed to a pointer to the first element. So when you pass a char [10][10]
(an array of size 10 of char [10]
) to a function it decays into a char (*)[10]
(a pointer to a char [10]
.
Change your function to accept either char [10][10]
or char (*)[10]
.
Upvotes: 3