Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   declaring function that returns a structure (http://www.go4expert.com/forums/declaring-function-returns-structure-t19928/)

jhgan 31Oct2009 09:09

declaring function that returns a structure
 
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
{
        int num_a=0, num_b=0;
};
//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++;
                                return count( str[idx], idx);
                case 'b':
                                (res.num_b)++;
                                idx++;
                                return count( str[idx], idx);
                case '\0':
                                return res;
        }
}


SaswatPadhi 31Oct2009 13:23

Re: declaring function that returns a structure
 
(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: CPP

struct result count( char str[], int idx )

accepts a character array and an integer.
But you are passing a character ... str[idx].

jhgan 31Oct2009 13:33

Re: declaring function that returns a structure
 
oo...


All times are GMT +5.5. The time now is 23:23.