Reputation: 29
I am trying to access all elements of this preinitialized char
pointer in 'c'. Here is the code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
char **s="Hello";
printf("%c",*(*&s+1));
}
This code should output "e", but doesn't. What am I doing wrong?
Also, how do I access all elements one by one?
Upvotes: 0
Views: 470
Reputation: 31
Assumed that you are not seeing the 'e' of the Hello, I highly recommend watching this post.
What to do when the pointer doesn't print the string properly
Just to summarize, when you reference the pointer s, it is only reading the H of Hello (since that is how the pointer of string works - it points to the first character of the string, like s[0]), and that results your code in printing out H only.
Most importantly, your pointer is double-pointer, which is incorrect.
Try it in this way.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char s[] = "Hello";
printf("%s\n",s);
}
Upvotes: 0
Reputation: 223699
The type of s
is incorrect. The string constant "Hello"
has array type which can decay to type char *
but you're assigning it to a variable of type char **
.
Change the type of s
to char *
and your code will output "e":
char *s = "Hello";
Also, looking at this:
*(*&s+1)
When *
comes right before &
they cancel each other out. So you can simplify this to:
*(s+1)
Or equivalently:
s[1]
Upvotes: 3