I have the following code:
int main(){
char **array;
char a[5];
int n = 5;
array = malloc(n *sizeof *array);
/*Some code to assign array values*/
test(a, array);
return 0;
}
int test(char s1, char **s2){
if(strcmp(s1, s2[0]) != 0)
return 1;
return 0;
}
I'm trying to pass char and char pointer array to a function, but the above code results in the following errors and warnings:
temp.c: In function ‘main’: temp.c:6:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration] temp.c:6:13: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default] temp.c:10:5: warning: implicit declaration of function ‘test’ [-Wimplicit-function-declaration] temp.c: At top level: temp.c:15:5: error: conflicting types for ‘test’ temp.c:15:1: note: an argument type that has a default promotion can’t match an empty parameter name list declaration temp.c:10:5: note: previous implicit declaration of ‘test’ was here temp.c: In function ‘test’: temp.c:16:5: warning: implicit declaration of function ‘strcmp’ [-Wimplicit-function-declaration]
I'm trying to understand what the problem is.
Best Answer
First of all, you should include the necessary header files. For
strcmp
you need<string.h>
, formalloc
<malloc.h>
. Also you need to at least declare test before main. If you do this you'll notice the following error:This indicates that
test()
should have achar *
as first argument. All in all your code should look like this:Edit
Please notice that
strcmp
works with null-terminated byte strings. If neithers1
nors2
contain a null byte the call intest
will result in a segmentation fault:Either make sure that both contain a null byte
'\0'
, or usestrncmp
and change the signature oftest
:Also your allocation of memory is wrong.
array
is achar**
. You allocate memory for*array
which is itself achar*
. You never allocate memory for this specific pointer, you're missingarray[0] = malloc(n*sizeof(**array))
: