Question:
C Question: pointers and structs?
2010-01-17 07:05:48 UTC
I've defined myself a list like this:

typedef struct list {
char key[30];
int freq;
struct list *next;
} list ;

So each node contains an array of 30 chars called the 'key', an int called freq and a pointer to the next node in the list.
My program crashes when I try to manipulate the lists, I'm new to C so I'm probably missing something (I still don't entirely get pointers..).
Here's an example from the main function:

int main( int argn, char **input ){
FILE *file;
list *data = malloc(sizeof(list));
data->freq = 1;
int n;
char d[500];
char *c;
if(argn>0){
file = fopen(input[1], "r");
n = fread(d,1,500,file);
c = d;
c[n]='\0';
c = lowercase(c);
c = purify(c);
data = readintolist(data,c);
fclose(file);
printf("%s\n", data->key );
} else {
printf("Error: No file found\n");
}

return 0;
}


Now before it even gets to the if statement, the program crashes as soon as it reaches the "data->freq = 1;" bit.
To make passing it around functions easier, I defined the data list as a pointer to the list, so I know that using "data.freq = 1;" won't work, I just don't know whats wrong! aha

Thanks in advance if you can help.
Three answers:
hijon89
2010-01-17 07:21:57 UTC
What kind of crash is occurring? Does the program segfault? The only thing that I see that could be a problem before "data->freq = 1" is this line "list *data = malloc(sizeof(list))" Just to be sure, try doing sizeof(struct list) instead.



Another problem I see is that your if statement checks if (argn>0), but the argument list includes the program name so it is always > 0. You want to check if argn > 1 (or in your case if argn == 2). In the next line you correctly read from input[1], since input[0] is going to be the program name.
oops
2010-01-17 07:22:00 UTC
Are you sure that's where it's crashing? How do you know? I'm not so sure, I think the problem is that you are trying to read a file even though you haven't passed one to the program.



change this:



if(argn>0)



to this:



if(argn>1)
maragh
2016-11-05 15:39:20 UTC
If this application is providing you with errors please do this when which run void InputEmployeeRecord(worker *ptrEmployee); it is going to be void InputEmployeeRecord(worker &ptrEmployee); else specify extra what you choose


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...