-1

This is C code snippet:

 int main()
 {
   char *names=[ "tom", "jerry", "scooby" ];
   printf("%s", *names[0]);// prints t
   printf("%s", *names[1]);// prints j
  // how to print full word "tom", or full word "jerry"
}

As stated earlier, I want my output to be: tom jerry scooby So using pointers how do I print the whole thing?

4
  • 1
    Change char *names to char *names[]. Remove * before printf arguments. Look at this: ideone.com/bokCN5 Commented Oct 14, 2016 at 11:52
  • 1
    change names to be an array of pointer, otherwise it can only hold 1 string. Also the [ should be a {. Commented Oct 14, 2016 at 11:53
  • 1
    @ashley It looks like you should re-read the chapter of your C book that explains strings. Commented Oct 14, 2016 at 11:54
  • 1
    Also, use {} instead of [] to enclose intializers. Commented Oct 14, 2016 at 11:58

1 Answer 1

3

Does it compile? Because your array initialization is not correct. To properly declare an array and print them, you can do:

#include <stdio.h>

int main(void)
{
   char *names[]= { "tom", "jerry", "scooby" };
   printf("%s %s %s\n", names[0], names[1], names[2]);
   return 0;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Oh sorry, i forgot to add the [].
Can you tell me the output of
Can you tell me the output of: printf("%s\n",names[0])?
Thanks, it is tom and jerry. Thank you very much. Have a great day.
names[0] is the first element in the array names and is a pointer to a string literal. Printing names[0] would print tom.

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.