Reputation: 65
I'm experimenting with C void functions and strings. I've tried this program:
#include <stdio.h>
#include <string.h>
void print(char** test);
int main(){
char* test = "abcdef";
print(&test);
return 0;
}
void print(char** test){
for(int i=0;i<strlen(*test);i++)
printf("%c\n",*test[i]);
}
It prints for me the first a A �
then segmentation fault. But after changing *test[i]
to *(*test+i)
which is pretty much the same thing it works for me as expected.
Is there any subtle difference *test[i]
and *(*test+i)
if not, why my code works in second examples meanwhile it doesn't in the first ?
Upvotes: 2
Views: 124
Reputation: 12817
test
is a char**
. As Some programmer dude commented, the []
takes precedence over the *
so your for loop is executed like this:
*test[0] == *(test[0]) == 'a'
*test[1]
== *(test[1])
== *(some other address that is saved in memory after &test
) => UBEither use one indirection in the whole program (i.e. *, not ** and &test
), or use (*test)[i]
Upvotes: 4