0

Is it possible to create an array like this: char name[] = {"Zed", "Roc", "Blanca"};

and then be able to:

printf("%s, %s and %s are my next-door neighbors.\n", name[0], name[1], name[2]);

I've tried it, but I keep getting errors on the array, saying "error: excess elements in char array initializer" and "error: (near initialization for ‘name’)" when I try to make the binary (did I use that right?).

I also get "warning: format ‘%s’ expects argument of type ‘char *’, but argument [2-4] has type ‘int’ [-Wformat]" Character strings get a %s as a format specifier, don't they?

I'm learning C for the first time. I have a background in JavaScript, so I know how to work with arrays, which is why I ask about this; what seems obvious to me doesn't seem to work. Different language, different rules, right?

I'm also using "Learn C the Hard Way" to learn. I'll laugh if this is something that will easily be explained next chapter (spoilers).

2
  • Yes, you are using arrays properly. It's explicit pointers and the lack of a primitive string type in C that you are going to have fun learning! :) Commented Dec 7, 2013 at 2:05
  • Haha - I look forward to it ;) The joys of learning a new language, in my experience. Having to recall the concepts you've previously learned, and, at the same time, having to know when to throw them out of the window. Commented Dec 7, 2013 at 2:18

1 Answer 1

8

Try:

char* name[] = {"Zed", "Roc", "Blanca"};

Remember, a string is an array of chars, or a pointer to char, not just a char. What you had there was one array of chars, but it needs an array of strings.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup! Now it's working, and more importantly, it makes sense. A string is an array of chars...something I'll definitely take with me along the way. Thanks so much :)

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.