Search code examples
cpointersstructure

C , Pointers to structure in functions formatting


I'm a beginner programmer and wish to ask how to properly use a pointer to a structure in a function (in this case getRectangleDimension() ).

I have attempted this question for a couple of hours and search this site an found nothing useful. Any help is appreciated!!

#include <stdio.h>
#include <stdlib.h>
#define  UNKNOWN  -1
struct  rectangle
{
    int width;
    int length;
    int area;
};

void  getRectangleDimension(struct  rectangle* B)
{
    printf("what  is  the  width?\n");
    scanf("%d",  &B.width);
    printf("what  is  the  length?\n");
    scanf("%d",  &B.length);
}

int main()
{
    struct  rectangle  myBox;
    myBox.width=UNKNOWN;
    myBox.length=UNKNOWN;
    myBox.area=UNKNOWN;
    getRectangleDimension(&myBox);
    printRectangle(myBox);
    return 0;
}

Solution

  • The pointer has to be dereferenced. One does this with the * operator. This is a very common operation and the C language uses B->width as a stand-in for (*B).width, which one should defiantly use. The scanf requires a pointer, &B->width.