Total Pageviews

Friday 4 May 2012

Structures


Structures
Structures in C are similar to records in Pascal. For example:

                struct gun
                            {
                            char name[50];
                            int magazinesize;
                            float calibre;
                            };

              struct gun arnies;

defines a new structure gun and makes arnies an instance of it.

NOTE: that gun is a tag for the structure that serves as shorthand for future declarations. We now only need to say struct gun and the body of the structure is implied as we do to make the arnies variable. The tag is optional.

Variables can also be declared between the } and ; of a struct declaration, i.e.:
                struct gun
                            {
                            char name[50];
                            int magazinesize;
                            float calibre;
                            } arnies;

struct's can be pre-initialised at declaration:

struct gun arnies={"Uzi",30,7};

which gives arnie a 7mm. Uzi with 30 rounds of ammunition.
To access a member (or field) of a struct, C provides the . operator. For example, to give arnie more rounds of ammunition:
arnies.magazineSize=100;


  1. What will be printed as the result of the operation below:
    main()
    {
        char *ptr = ” Cisco Systems”;
        *ptr++; printf(“%sn”,ptr);
        ptr++;
        printf(“%sn”,ptr);
    }
    Answer:Cisco Systems
    isco systems
  2. What will be printed as the result of the operation below:
    main()
    {
        char s1[]=“Cisco”;
        char s2[]= “systems”;
        printf(“%s”,s1);
    }
    Answer: Cisco
  3. What will be printed as the result of the operation below:
    main()
    {
        char *p1;
        char *p2;
        p1=(char *)malloc(25);
        p2=(char *)malloc(25);
        strcpy(p1,”Cisco”);
        strcpy(p2,“systems”);
        strcat(p1,p2);
        printf(“%s”,p1);
    }
    Answer: Ciscosystems
  4. The following variable is available in file1.c, who can access it?:
    static int average;
    
    Answer: all the functions in the file1.c can access the variable.
  5. WHat will be the result of the following code?
    #define TRUE 0 // some code
    while(TRUE)
    {
        // some code
    }
    Answer: This will not go into the loop as TRUE is defined as 0.
  6. What will be printed as the result of the operation below:
    int x;
    int modifyvalue()
    {
        return(x+=10);
    }
    int changevalue(int x)
    {
        return(x+=1);
    }
    void main()
    {
        int x=10;
        x++;
        changevalue(x);
        x++;
        modifyvalue();
        printf("First output:%dn",x);
        x++;
        changevalue(x);
        printf("Second output:%dn",x);
        modifyvalue();
        printf("Third output:%dn",x);
    }
    Answer: 12 , 13 , 13

No comments:

Post a Comment