1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

declaring function that returns a structure

Discussion in 'C' started by jhgan, Oct 31, 2009.

  1. jhgan

    jhgan New Member

    Joined:
    Oct 31, 2009
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Hi, anyone knows why the highlighted words cause syntax errors?
    Please advise.

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    //declare structure
    struct result
    {
            [COLOR=Red]int num_a=0, num_b=0;[/COLOR]
    };
    //declare function prototype 
    struct result count( char str[], int idx );
    
    int main()
    {
            char str[] = "acdefAbbA";
            struct result res = count( str, 0 );
            /*char *pa=res.num_a, *pb=res.num_b;*/
            
            printf( "num a = %d and num b = %d\n", res.num_a, res.num_b );
            // should output : "num_a = 1 and num_b = 2"
            
            
            return 0;
    }
    
    struct result count( char str[], int idx )
    {
            switch( str[idx] )
            {
                    struct result res;
                    case 'a':
                                    (res.num_a)++;
                                    idx++;
                                    [COLOR=Red]return count( str[idx], idx);[/COLOR]
                    case 'b':
                                    (res.num_b)++;
                                    idx++;
                                    [COLOR=Red]return count( str[idx], idx);[/COLOR]
                    case '\0':
                                    return res;
            }
    }
     
    Last edited by a moderator: Oct 31, 2009
  2. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    (1) int num_a=0, num_b=0;

    This one causes error because C (or C++) does not allow in-struct (or in-class) initialization of non-const static member variables.
    You should define the struct without initializations and then initialize num_a and num_b to 0 whenever you declare a new variable of that struct type.

    (2) return count( str[idx], idx);

    The count function you have defined :
    Code:
    struct result count( char str[], int idx )
    accepts a character array and an integer.
    But you are passing a character ... str[idx].
     
  3. jhgan

    jhgan New Member

    Joined:
    Oct 31, 2009
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    oo...
     

Share This Page