从二维字符数组中打印字符串

时间:2015-11-13 16:00:48

标签: c arrays string char printf

我已经环顾四周并为此尝试了不同的语法,但我似乎无法让它发挥作用。我知道这是基本的,但它不需要花太长时间才能搞清楚。

我有角色阵列......

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

然后我从该数组中生成一个随机元素......

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

然后我尝试将其打印出来,但它失败了......

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

输出

What is (null) 's number?

和lldb显示printf语句跳转到...

libsystem_c.dylib`strlen:
->  0x7fff9a596d32 <+18>: pcmpeqb (%rdi), %xmm0
    0x7fff9a596d36 <+22>: pmovmskb %xmm0, %esi
    0x7fff9a596d3a <+26>: andq   $0xf, %rcx
    0x7fff9a596d3e <+30>: orq    $-0x1, %rax

3 个答案:

答案 0 :(得分:2)

数组索引从0开始。

对于char *roster[2][14];,可能的索引是

roster[0][random];
roster[1][random];

答案 1 :(得分:2)

c中的数组从0开始,所以如果你声明:

char *roster[2]

然后你只能引用名册[0]和名册[1]。

答案 2 :(得分:1)

delete from TableName where info not in 
(select min(info) from TableName group by ID,Age);

您可以访问索引超出范围,调用 未定义的行为

因为您可以将索引设为printf("What is %s 's number?", roster[2][random]); 而不是 roster[0][random] and roster[1][random],因为它被声明为 -

roster[2][random]

您可以打印这些 -

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

或 -

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