2016-11-19 49 views
-1

我试图将字符串数组的位置作为int数组的参数传递,并且我得到了无效的间接符作为错误。我想计算我随机生成并抓到的小精灵的频率。我做了一些相当多的研究,但仍然无法理解它的概念。附:我的讲师正在教C的过时版本,以便介绍printf(s)。将字符数组转换为值并将其放入C中的int数组中

int encounter() { 
    //list of pokemons 
    char pokemon[5][10] = {"Magikarp", "Zubat", "Eevee", "Magmar", "Pikachu"}; 
    int type[5] = {0,0,0,0,0}; 
    int i; 
    int a=0; 
    //random number generator from 0 - 4 
    srand(time(NULL)); 
    i = (rand() % 5); 

    //prints out the pokemon name 
    printf("A wild %s appeared! \n", pokemon[i]); 

    type[pokemon[i]] += 1; 

    for(a=0; a<6; a++) { 
    printf(type[a]); 
    } 
    return 0; 
} 
+1

“***我的讲师教的C过时的版本,所以介意的printf(S)。***” 是什么意思呢? –

+2

您使用的C版本不能过时:您正在使用内联注释,直到C99时才会使用内置注释。 – yellowantphil

+0

间接问题在这里是'type [pokemon [i]] + = 1;'。用简单的'type [i] + = 1;'替换那个代码,因为pokemon [i]是一个char数组。 –

回答

1

线:

type[pokemon[i]] += 1; 

不正确。

pokemon[i]有型号char*;即它是一个指针,不应该用来索引type数组。我想你的意思是用i索引type数组。它应该是

type[i] += 1; 

此外,打印类型的循环是错误的。它迭代6次,但type数组只有5个元素(包括0..4)。最后,printf功能想要的格式字符串作为第一个参数(它已经开始的时间),所以它应该是:

for(a = 0; a < 5; a++) { 
    printf("%d\n", type[a]); 
} 
+0

我不知道pokemon [i]是一个指针,谢谢澄清。 –

1

三两件事:

  1. 随着type[pokemon[i]] += 1;你行试图传递一个字符串作为数组的索引。你应该做的是type[i]
  2. for(a=0; a<6; a++)因为type有五个元素,而不是六个,所以会出界。
  3. printf(type[a])无效C; printf只能通过指定整数的有效格式字符串打印整数。尝试printf("%d\n", type[a]);
+0

感谢您的帮助!我的问题已解决。 –

-1

在你的例子中i代表生成的pockemon索引。如果它是随机产生的,即其值为3,则它指的是称为“Magmar”的痘痘(pockemon[3])。类型数组包含捕获的小宠物的数量,所以它必须由pockemon索引本身索引,而不是通过字符串数组的位置,这是没有意义的。

正确type[pokemon[i]] += 1;type[[i]] += 1;

+0

双括号? – pat

相关问题