0

I have the following code:

include <stdlib.h>

typedef struct foo{
    int x;
}Foo;

void funcY(Foo *f1)
{
    printf("%d", f1.x);
}

void funcX(Foo *f1)
{
    printf("%d", f1.x);
    funcY(f1);            <---- is this correct?
}

int main()
{
    Foo *foo1 = (struct foo *)malloc(sizeof(struct foo));
    foo1.x = 10;
    funcX(foo1); 
    return 0;
}

I don't know exactly how to label this problem. What is the best way for me to approach this?

1
  • What is the intended behavior? Does it work as intended? What happens when you try to compile and run it, and how is that different from what you want? Commented Jun 28, 2014 at 18:18

2 Answers 2

2
funcY(f1);            <---- is this correct?

Yes, this particular line is correct. However, several other parts that aren't: specifically, accessing struct members by pointer needs -> operator, rather than a dot:

printf("%d", f1->x);

Another small issue is that one should not cast malloc in C:

Foo *foo1 = malloc(sizeof(struct foo));

Finally, you are missing a call to free(foo) to deallocate malloc-ed memory. Note that you do not have to use malloc - allocate the struct in the automatic store, and use & to access its address:

int main()
{
    Foo foo1;
    foo1.x = 10;
    funcX(&foo1); 
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was in a rush and didn't catch my errors.
0

funcY(f1) is correct - it passes the Foo pointer to funcY, and since funcY accepts a Foo pointer we can assume it'll work as intended.

printf("%d", f1.x);, however, is not correct. f1 is a Foo pointer, not a Foo. To access it's x field you need to derefer it first - (*f1).x - or use the sytactic sugar f1->x.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.