2

I've looked around and tried different syntax's for this but I can't seem to get it to work. I know this is elementary, but it's something that shouldn't take too long to figure out.

I have the character array...

char *roster[2][14] = {
      {"13", "10", "24", "25", "15", "1", "00", "4", "11", "23", "22", "32", "3", "35"},
      {"Isaiah Briscoe", "Jonny David", "EJ Floreal", "Dominique Hawkins", "Isaac Humphries", "Skal Labissiere", "Marcus Lee", "Charles Matthews", "Mychal Mulder", "Jamal Murray", "Alex Poythress", "Dillon Pulliam", "Tyler Ulis", "Derrick Willis"}
    };

Then I'm generating a random element from that array...

random = rand() % 14;
printf("What is %s 's number?", roster[2][random]);

Then I try to print it out, but it fails...

printf("What is %s 's number?", roster[2][random]);

It outputs

What is (null) 's number?

and lldb shows that the printf statement jumps into...

libsystem_c.dylib`strlen:
->  0x7fff9a596d32 <+18>: pcmpeqb (%rdi), %xmm0
    0x7fff9a596d36 <+22>: pmovmskb %xmm0, %esi
    0x7fff9a596d3a <+26>: andq   $0xf, %rcx
    0x7fff9a596d3e <+30>: orq    $-0x1, %rax
2
  • Fails how? Whats the output? Commented Nov 13, 2015 at 16:02
  • random is a well known system function name, defined in stdlib.h. It is a bad idea to declare a variable name the same as a system function name. Commented Nov 14, 2015 at 16:23

3 Answers 3

2

Array index starts from 0.

For char *roster[2][14];, the possible indices are

roster[0][random];
roster[1][random];
Sign up to request clarification or add additional context in comments.

Comments

2

Arrays in c start at 0, so if you declare:

char *roster[2]

Then you can only reference roster[0] and roster[1].

Comments

1
printf("What is %s 's number?", roster[2][random]);

You access index out of bound invoking undefined behaviour .

Because you can have indices roster[0][random] and roster[1][random] not roster[2][random] because it is declared as -

char *roster[2][14] = {
  {"13", "10", "24", "25", "15", "1", "00", "4", "11", "23", "22", "32", "3", "35"},
  {"Isaiah Briscoe", "Jonny David", "EJ Floreal", "Dominique Hawkins", "Isaac Humphries", "Skal Labissiere", "Marcus Lee", "Charles Matthews", "Mychal Mulder", "Jamal Murray", "Alex Poythress", "Dillon Pulliam", "Tyler Ulis", "Derrick Willis"}
};

You can print these -

printf("What is %s 's number?", roster[1][random]);

Or -

printf("What is %s 's number?", roster[0][random]);

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.