praiseHellRaiseDale
praiseHellRaiseDale

Reputation: 2270

Why doesn't struct exist after declaration inside of function?

I've tried a lot of simple examples of this and haven't gotten any to work.

My goal is to have a function which declares a struct internally, sets the values of the struct, and then returns the struct.

struct getData(void){
    typedef struct{
        int count1;
        int count2;
    } MyStruct;

    MyStruct myData;

    myData.count1 = 5;
    myData.count2 = 6;

    return myData;
};

int main(void) {
    struct myData = getData()

    printf("count1: %i", myData.count1);
    printf("count2: %i", myData.count2);
}

Every example I've found does something similar to this, but for some reason it's not finding my struct called MyStruct. Exact error is:

error: expected identifier or ‘(’ before ‘void’
 struct getData(void){
                ^~~~

The error I keep getting makes me think it doesn't like the struct inside the function.

Upvotes: 0

Views: 805

Answers (2)

neutrino_logic
neutrino_logic

Reputation: 1299

I think the more standard way to write what you're after is this, using an independent definition of the struct, and then using a pointer for the function call. As written your code seems to have some scope issues (declaring a struct typedef inside a function, hmmm...) [Incorrect->] plus I don't believe structs can be passed around that way in C, I'm pretty sure you have to use pointers. [Edit oops this is incorrect! See comments]

#include<stdio.h>

typedef struct {
    int count1;
    int count2;
    } MyStruct;

void getData (MyStruct* myDataPtr) {
    myDataPtr->count1 = 5;    //note pointer access notation ->
    myDataPtr->count2 = 6;
};

int main(void) {
    MyStruct myData;
    MyStruct* sPtr = &myData;  //create pointer to struct, assign to myDaya
    getData(sPtr);            //pass pointer to function
    printf("count1: %i \n", myData.count1);
    printf("count2: %i \n", myData.count2);
}

Outputs:

count1: 5
count2: 6

Upvotes: 0

Your problem seems to be a confusion regarding the usage of the struct keyword. You don't do struct myData to declare a variable named myData that is of struct type, because there isn't really a struct type. What you do is struct myData <SOMETHING> to define <SOMETHING> as being a new data type named struct myData. You can then say struct myData dat;, thereby declaring that dat is a variable of type struct myData.

You're also demonstrating the same confusion at the top, where you have struct getData(void)... you're attempting to declare getData as a function returning a struct, but you'd really have to do something like struct myData getData(void) to declare a function returning type struct myData.

Upvotes: 1

Related Questions