Originally Posted by
laserlight
but if you have a pointer member then you need to allocate memory for the string contents itself.
But let's say, hypothetically, that you not only want to store the song's name, but also aliases to the song's name, e.g., some songs are popularly known by alternative names because fans like some of the lyrics so much that they use the lyrics as the song's name, even though officially it isn't its name. Then, maybe you really would store a list of names, perhaps with the first name as the official name, and other names as the aliases, in which case a member like this is fine:
Code:
char *names[MAX_NUM_NAMES];
Exactly, so with my current implementation, isn't it correct? I defined MAXNAMESIZE as 20 in the program header, so when I stated char* name[MAXNAMESIZE] I have a pointer member with memory allocated for the string contents. Is this incorrect?
Here is my code as it stands currently. No compile errors, I'm just stuck.
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAXNAMESIZE 20
typedef struct song {
char* name[MAXNAMESIZE];
int rating;
int numTimesPlayed;
} Song;
Song* readAlbum(const char* filename, int* lenPtr);
void printAlbum(Song* album, int len);
int main(int argc, char* argv[])
{
int lenPtr;
char *len = readAlbum(argv[1], &lenPtr);
printAlbum(*len, 3);
return 0;
}
Song* readAlbum(const char* filename, int* lenPtr)
{
FILE* fp; //Declare file pointer
if((fp = fopen(filename, "r"))==NULL) //Open file, return null if unable to open
{
printf("The file could not be opened. \n");
return NULL;
}
fscanf(fp, "%d", lenPtr);//scan for the first line in the file
Song* album=malloc(sizeof(Song)**lenPtr);
int i = 0;
for(i = 0; i < *lenPtr; i++)
{
fscanf(fp, "%s %d %d", *album[i].name, &album[i].rating, &album[i].numTimesPlayed);
}
fclose(fp);
return album;
}
void printAlbum(Song* album, int len)
{
int i =0;
for(i = 0; i < len; i++)
{
printf("%s %d %d\n", *album[i].name, album[i].rating, album[i].numTimesPlayed);
}
}