开发者

How to show an array

I've got this:

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

Now I want something like this: printf("Desired Element %c, array[w]); but it fails, why?


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

will try to print a character (%c), but it will fail since array[w] contains a string.

Try using %s instead:

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


Probably because it's not %c but %s for strings

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

Don't forget to check wether w is valid.


Don't print the friend name (a string) as character (%c), use %s.

Also, arrays in C start at index 0, making them start at 1 instead is weird and might make it easier to confuse yourself and access past the end.


the %c element in your debug string prints a character. If you want to print the string try:

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


Use printf("Desired Element %s, array[w]) instead of with %c. You're printing a string, not a character.


There are many oddities in the program. Here is a cleaned-up version.

#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 */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜