开发者

Struct not compiling?

I'm trying to learn structs and have the following code below in the .h and .c files respectively.

    typedef struct{
    int lengthOfSong;
    int yearRecorded;
} Song;

Song makeSong (int length, int year);
void displaySong(Song theSong);

.c:

Song makeSong(int length,开发者_StackOverflow社区 int year){
    Song newSong;
    newSong.lengthOfSong = length;
    newSong.yearRecorded = year;

    displaySong(newSong);

    return newSong;
}

void displaySong(Song theSong){
    printf("This is the length of the song: %i \n This is the year recorded: %i", theSong.lengthOfSong, theSong.yearRecorded);
}

For some reason i'm getting the error: song.c:1: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘makeSong’ song.c:11: error: expected ‘)’ before ‘theSong’

Am I doing something wrong?

Edit main (the other functions were already working):

   #include <stdio.h>
#include "math_functions.h"
#include "song.h"

main(){
    int differ = difference(10, 5);
    int thesum = sum(3, 7);
    printf("differnece: %i, sum: %i \n", differ, thesum);
    Song theSong = makeSong(5, 8);

}


displaySong takes an argument theSong and you're trying to use newSong

You'll also need to #include "song.h" from song.c - the error message looks like you skipped that.


You need to #include "song.h" in the .c file where makeSong() and displaySong() are defined. Otherwise the compiler does not know how to create objects of type Song.


With the earlier corrections made, still you are getting error because program is not including song.h in both the header files. Source files need to include song.h ( i.e., in main.c and song.c, guessing you have named source files like that ). Also -

Song makeSong(int length, int year){
    Song newSong;
    newSong.lengthOfSong = length;
    newSong.yearRecorded = year;

    displaySong(newSong);

    return newSong;
}

can be simplified to -

Song makeSong(int length, int year){

    Song newSong = { length, year } ;

    displaySong(newSong);

    return newSong;
}


Edit: Messed typedef in my previous answer:

typedef struct NAME1 {
    ...
} NAME2;

NAME1 names the struct, NAME2 the explizit type struct NAME1. Now NAME1 can't be used without struct in C, NAME2 can:

struct NAME1 myvar1;
NAME2 myvar2;

You're getting the issue cause Song isn't recognizes as a variable type (without the struct keyword before).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜