3

I am trying to understand the below program syntax with the structure.

struct virus
{
    char signature[25] ;
    char status[20] ;
    int size ;
} v[2] = {
    "Yankee Doodle", "Deadly", 1813,
    "Dark Avenger", "Killer", 1795
    };

main( )
{
    int i ;
    for ( i = 0 ; i <=1 ; i++ )
        printf ( "\n%s %s", v[i].signature, v[i].status ) ;
} 

What does v[2] means here? I have never seen these kind of declarations before so bit of confuse over there. Can anyone explain me what does v[2] means here?

4

4 回答 4

4

It makes v as array of virus structure with 2 elements and assigns values as defined in the rvalue.

Its similar to

struct virus
{
    char signature[25] ;
    char status[20] ;
    int size ;
};

struct virus v[2] = {
    "Yankee Doodle", "Deadly", 1813,
    "Dark Avenger", "Killer", 1795
};
于 2013-06-15T18:27:25.983 回答
0
struct virus
{
    char signature[25];
    char status[20];
    int size;
} v[2] = /* ... */

It will define the identifier v as an array of 2 struct virus, initialized with the contents of the array initializer.

You can print its value to see what happens:

#include <stdio.h>

int i;

for (i = 0; i < 2; i++)
    printf("%s %s %d\n", v[i].signature, v[i].status, v[i].size) ;
于 2013-06-15T18:27:33.873 回答
0

This declares an array of struct virus having and initializing two elements of the array.

The declaration coming before the main( ) scope means the array will have global scope and static initialization.

于 2013-06-15T18:28:01.490 回答
0

The array v is an array of two struct virus. In the example the definition of struct virus, the array v[] and its initialisation are performed in one. The definition and declaration could be separated thus:

struct virus
{
    char signature[25] ;
    char status[20] ;
    int size ;
} ;

struct virus v[2] = { "Yankee Doodle", "Deadly", 1813,
                      "Dark Avenger", "Killer", 1795 } ;

Note also that strictly speaking the initializer in the example (and above) is mal-formed and should in fact be.

struct virus v[2] = { { "Yankee Doodle", "Deadly", 1813 },
                      { "Dark Avenger", "Killer", 1795  } } ;

I would expect a compiler to issue a warning in the first instance unless the warning level were set too rather low.

于 2013-06-15T18:58:40.357 回答