0

I have been googling for a few days trying to find the correct syntax in C. to print an array in a set out of order arrangement. I am new to C but know php, Java well. Am I using the wrong logic approach?

What I would like to print out is

     "Here is your order, 2B 3C 1A"

I have tried using the following type of code but get,

     @[2] (null)[3] (null)[1]
     segmentation fault

     char *aa="1A";
     char *bb="2B";
     char *cc="3C";
     char * zz[]={aa,bb,cc};
     g_print("Here is your order, %s[2] %s[3] %s[1]",zz);

thanks Art

2
  • 1
    for(i=0;i<3;i++) printf("%s ", zz[i]);, change the order you like. Commented Dec 16, 2013 at 10:34
  • ... and read the documentation of printf. Commented Dec 16, 2013 at 10:36

2 Answers 2

2

You have to print each string in the array:

g_print("Here is your order, %s %s %s",zz[1], zz[2], zz[0]);

Note the indexing!

If the number of items is set during runtime, you have to use a loop:

g_print("Here is your order,");
for (size_t i = 0; i < some_upper_limit; ++i)
    g_print(" %s", zz[i]);

Also note that you declare the aa, bb and cc variables wrong. You should either declare them as arrays, or as pointers to constant strings. That's because string literals are constant.

So:

char aa[]="1A";
char bb[]="2B";
char cc[]="3C";

or

const char *aa="1A";
const char *bb="2B";
const char *cc="3C";
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @Joachim Pileborg for the two alt's, now it makes sense. thx Art
2

use:

 g_print("Here is your order, %s %s %s",zz[1], zz[2], zz[0]);

array indices start with 0. The contents of strings is not evaluated for the array indices.

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.