Reputation: 289
I'm trying to change the 'lineNumber' field of this struct:
typedef struct occurrenceType Occurrence;
struct occurrenceType {
char* line;
int lineNumber;
int wordNumber;
Occurrence *next;
};
using this bit of code
Occurrence *occur;
occur=(Occurrence*)malloc(sizeof(Occurrence));
(*occur).lineNumber=34;
but when I print (*occur).lineNumber it comes to be zero. I've tried several different configurations with the struct and the occur pointer, but nothing seems to be working. Can anyone see what I'm doing wrong? Thanks!
EDIT: The full call looks like this:
inFile=fopen(argv[1],"r");
while(fgets(line,100,inFile)!=NULL) {
if(strstr(line,argv[2])!='\0') {
(*occur).line=line;
(*occur).lineNumber=34;
(*occur).next=(Occurrence*)malloc(sizeof(Occurrence));
occur=(*occur).next;
printf("%d",(*occur).lineNumber);
}
count++;
}
It reads a file line by line and searches for a key provided in the command line, then adds a struct to a linked list for each occurrence.
Upvotes: 0
Views: 87
Reputation: 89
You are printing the field of the newly malloc'ed structure. Try reversing the last two lines:
occur=(*occur).next;
printf("%d",(*occur).lineNumber);
to:
printf("%d",(*occur).lineNumber);
occur=(*occur).next;
Couple other comments, based on the context of the code snippet you gave us: You should be setting that structure to zero, as malloc
won't do that for you. It'll have garbage, and I'm assuming that you're checking the field next
for NULL
as you are walking down the linked list. Changing your call to calloc()
would fix this.
Second, why are you assigning the line pointer to the field line
? That's going to be the same for every structure, and the content of it will be the last thing read from the file. I'm assuming you're wanting to save off the line read. Try making it another buffer (or calloc()
it as well), and strcpy()
the found data to it.
Upvotes: 1