Reputation: 185
I'm trying to learn about pointers in the C language. But I have a question regarding dereferencing them.
This piece of code works fine, it displays 'i' as I desire.
#include <stdio.h>
void myfunction(char** str);
int main()
{
char *name = "Gianni";
myfuntion(&name);
return 0;
}
void myfunction(char** str){
char* test = *str;
printf("%c", test[1]);
}
But what I guessed to have the same result turns out to be a little bit different. My question is why do I not get the same result from the second piece of code?
I dereferenced the pointer so it points to the first character again and can read it until the '\0' terminator. So I thought it would be possible to display the single characters here as well.
#include <stdio.h>
void myfunction(char** str);
int main()
{
char *name = "Gianni";
myfuntion(&name);
return 0;
}
void myfunction(char** str){
printf("%c", *str[1]);
}
Upvotes: 1
Views: 78
Reputation: 30906
This is precedence issue.(Array subscript []
has higher precedence than dereference *
). You should try
(*str)[1]
This will give you the correct result. In earlier case (In Code-2) you had undefined behavior. You were de-referencing str[1]
which is pointing to out of bound memory.
So initially what you were doing in Code-2
*str[1] --> *(*(str+1))
Now what we did,
(*str)[1] --> *((*str)+1)
Well in the modification you are basically getting the address of the array (string literals are array which decayed into pointer) and then you index into correct position - which will give you the correct result.
Well if you check earlier example you will see the similarity. Earlier code (Code-1) you print temp[1]
which is *(temp+1)
But what is temp
? In the line before you did this temp = *str
so what is it you are doing?
*(temp+1) --> *(*str+1) --> *((*str)+1)
Upvotes: 5