0

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?

5
  • I want to access all elements one by one. Commented Nov 26, 2019 at 15:49
  • 2
    Does this compile? Without warnings? And please edit and add a question. You’ve now only included a mention what you’re trying to do but not what’s wrong. Or what this “e” is Commented Nov 26, 2019 at 15:50
  • This gives me more warnings that there are lines of code. Here's a tip: if you want to print all chars of "Hello" individually with the %c specifier, you'll need a loop. Commented Nov 26, 2019 at 15:51
  • Always use your compiler's warnings and head them. With gcc, I use -Wall -Wextra -pedantic. This would have found the problem. Commented Nov 26, 2019 at 16:01
  • @SamiKuhmonen No, it is giving warning like warning: initialization from incompatible pointer type [-Wincompatible-pointer-types] char **s="Hello"; Commented Nov 27, 2019 at 3:09

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.