ColinO
ColinO

Reputation: 59

Typedef struct and passing to functions

I'm trying to declare a typedef struct array and then pass it to a function but i'm getting errors because i'm not exactly certain the proper syntax, help would be greatly appreciated. Here is my code:

#include <stdlib.h>
#include <stdio.h>

#define MAX_COURSES 50

typedef struct courses      //creating struct for course info
{
    int Course_Count;
    int Course_ID;
    char Course_Name[40];
}course;    

void Add_Course(course , int *);

int main()
{
    course cors[MAX_COURSES];
    int cors_count = 0;

    Add_Course(cors, &cors_count);
    return 0;
}

void Add_Course(course cors, int *cors_count)
{
    printf("Enter a Course ID: ");  //prompting for info
    scanf("%d%*c", cors.Course_ID);
    printf("Enter the name of the Course: ");
    scanf("%s%*c", cors.Course_Name);

    cors_count++;   //adding to count

    printf("%p\n", cors_count);
    return;
}

The errors i'm getting are:

error: incompatible type for argument 1 of ‘Add_Course’

test2.c:28:6: note: expected ‘course’ but argument is of type ‘struct course *’

test2.c: In function ‘Add_Course’:

test2.c:81:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]

Any help would be appreciated

Upvotes: 1

Views: 5123

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

In your Add_Course() function, the first argument is of type course but what you're passing is an array of type course which are not the same. You need to have a pointer to course as the first argument if you want to pass an array.

Next, scanf("%d%*c", cors.Course_ID); is also wrong, scanf() expects the argument to the format specifier as a pointer to the variable. You need to provide the address of the variable. Also, printf("%p\n", cors_count); should obviously be printf("%d\n", *cors_count);.

That said, cors_count++; is not probably what you wanted to have there. You want to increment the value, not the pointer itself.

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You are passing an array to a function expecting an instance of struct course, try like this

Add_Course(cors[cors_count], &cors_count);

But then it will only be modified in Add_Course so you need

void Add_Course(course *cors, int *cors_count)
{
    printf("Enter a Course ID: ");
    /* this was wrong, pass the address of `Course_ID' */
    scanf("%d%*c", &cors->Course_ID);
    /* Also, check the return value from `scanf' */
    printf("Enter the name of the Course: ");
    scanf("%s%*c", cors->Course_Name);

    /* You need to dereference the pointer here */
    (*cors_count)++; /* it was only incrementing the pointer */

    return;
}

And now you can

for (int index = 0 ; index < MAX_COURSES ; ++index)
    Add_Course(&cors[index], &cors_count);

although cors_count will be equal to MAX_COURSES - 1 in this case, it migh be useful after all.

Upvotes: 0

Related Questions