I am trying to pass an array of character strings (C style strings) to a function. However, I don't want to place a maximum size on length of each string coming into the function, nor do I want to allocate the arrays dynamically. Here is the code I wrote first:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun(char *s[])
{
printf("Entering Fun\n");
printf("s[1]=%s\n",(char *)s[1]);
}
int main(void)
{
char myStrings[2][12];
strcpy(myStrings[0],"7/2/2010");
strcpy(myStrings[1],"hello");
fun(myStrings);
return(0);
}
I got a seg fault when run and the following warning from the compiler: stackov.c: In function ‘main’: stackov.c:17: warning: passing argument 1 of ‘fun’ from incompatible pointer type stackov.c:5: note: expected ‘char *’ but argument is of type ‘char ()[12]’
However, when I change the main() to the following it works:
int main(void)
{
char myStrings[2][12];
char *newStrings[2];
strcpy(myStrings[0],"7/2/2010");
strcpy(myStrings[1],"hello");
newStrings[0]=myStrings[0];
newStrings[1]=myStrings[1];
fun(newStrings);
return(0);
}
Isn't array[2][12] the same thing as an array of character pointers when it is passed to a function?