Hey all
I'm halfway through a really tiny program, just to help me manage a few applicants I get. Wanted to code something in C purely to give me more experience with the language, but anyway.
Here's the code:
PHP Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXBUF 1024
typedef struct appl_def {
int id;
char *nick;
char *email;
int stage;
int task;
char *comments;
struct appl_def *next;
} applicant;
void getApplicants(void);
void listApplicants(void);
void addNode(int id, char *s);
/*
** tptr - Is a pointer to the top node of the linked list.
** cptr - Is a pointer to the current node of the linked list.
*/
applicant *tptr = NULL, *cptr = NULL;
int main(void)
{
getApplicants();
if (tptr != NULL)
listApplicants();
else
puts("There are currently no applicants.");
return 0;
}
void getApplicants(void)
{
int id;
FILE *fp;
char buf[MAXBUF];
if ((fp = fopen("applicants.txt", "r")) == NULL)
{
fprintf(stderr, "%s", "applicants.txt not found.\n");
exit(EXIT_FAILURE);
}
for (id = 1; ((fgets(buf, MAXBUF, fp)) != NULL); id++)
addNode(id, buf);
fclose(fp);
}
void listApplicants(void)
{
for (cptr = tptr; cptr != NULL; cptr = cptr->next)
printf("%d.) %s", cptr->id, cptr->nick);
}
/*
** nptr - Is a new node for the list.
*/
void addNode(int id, char *s)
{
applicant *nptr;
cptr = tptr;
if ((nptr = (applicant *) malloc(sizeof(applicant))) != NULL)
{
nptr->id = id;
nptr->nick = (void *)strdup(s);
nptr->next = NULL;
if (tptr == NULL)
tptr = nptr;
else
{
while (cptr->next != NULL)
cptr = cptr->next;
cptr->next = nptr;
}
}
else
{
fprintf(stderr, "%s", "Not enough memory to add applicant to linked list.\n");
exit(EXIT_FAILURE);
}
}
Now, my question is, I got a compiler warning complaining that 'assignment makes pointer from integer without cast', for this line:
nptr->nick = strdup(s);
I fixed it with:
nptr->nick = (void *)strdup(s);
However, whilst I've fixed the warning, I don't quite understand why lol. Could someone explain to me why the warning is now gone? I know it's something to do with the pointer that's returned from strdup(), and I think (void *) is casting it as a void pointer. I think that in turn means it can be used with any pointer type, which is why it works, but I'm not certain. Just need someone to say, "Yep, that's it!", or, "Nope, you muppet!".
Thanks in advance,
John.