2011-02-14 32 views
0

我有這樣的:如何顯示一個數組

int i, j, w; 
char *array[50]; 

int main() 
{ 
    array[1]= "Perro"; 
    array[2]= "Gato"; 
    array[3]= "Tortuga"; 
    array[4]= "Girafa"; 
    array[5]= "Canario"; 
    array[6]= "Rata"; 
    array[7]= "Leon"; 
    array[8]= "Tigre"; 
    array[9]= "Rinoceronte"; 
    array[10]= "Mosquito"; 
    for (i=1; i<11; i++) 
    { 

     printf("El elemento %i es %s \n", i, array[i]); 
    } 
    printf("Escoja el elemento deseado"); 
    scanf("%i", &w); 

    int c; 
    scanf("%i",&c); 
    return i; 
} 

現在,我想是這樣的:輸出(「所需的元素%C,數組[W]);但它失敗了,爲什麼

回答

1

不打印的朋友的名字(字符串)作爲字符(%c),使用%s

此外,在C開始在數組索引0,使他們從1開始,反而是奇怪的,可能更容易迷惑自己,進入過去的最後。

2
printf("Desired Element %c", array[w]); 

會嘗試打印一個字符(%c),但由於array [w]包含一個字符串,所以會失敗。

嘗試使用%S代替:

printf("Desired Element %s", array[w]); 
0

%c元素在你的調試字符串打印字符。如果你想打印字符串嘗試:

printf("Desired Element %s", array[w]); 
1

可能是因爲它不是%c%s字符串

printf("Desired Element %d\n", array[w]);

不要忘了請檢查是否w是有效的。

0

使用printf("Desired Element %s, array[w])而不是%c。您正在打印一個字符串,而不是一個字符。

0

程序中有很多古怪的東西。這是一個清理版本。

#include <stdio.h> /* necessary for printf/scanf */ 

#define ARRAY_LENGTH 10 /* use a constant for maximum number of elements */ 

int main() 
{ 
    /* Declare all variables inside main(), at the very top. Nowhere else. */ 
    int i; 
    int desired; /* use meaningful variable names, not x,y,z,etc */ 
    char *array[50]; 


    array[0]= "Perro"; /* arrays start at index 0 not 1 */ 
    array[1]= "Gato"; 
    array[2]= "Tortuga"; 
    array[3]= "Girafa"; 
    array[4]= "Canario"; 
    array[5]= "Rata"; 
    array[6]= "Leon"; 
    array[7]= "Tigre"; 
    array[8]= "Rinoceronte"; 
    array[9]= "Mosquito"; 

    for (i=0; i<ARRAY_LENGTH; i++) /* keep the loop clean */ 
    { 
     printf("El elemento %i es %s\n\n", i+1, array[i]); /* instead, add +1 while printing */ 
    } 

    printf("Escoja el elemento deseado: "); 
    scanf("%i", &desired); 
    getchar(); /* discard new line character somehow */ 

    printf("El elemento %i es %s\n", desired, array[desired-1]); 



    getchar(); /* wait for key press before exiting program */ 
    return 0; /* always return 0 */ 
}