0

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.

3
  • 1
    This is C code, not C++. In C++ it's necessary to cast the result of malloc. In C it's a bad idea, because in C that's just telling the compiler to shut up about failure to include necessary header. Commented Dec 7, 2013 at 6:29
  • 1
    Also note that instead of (*occur).lineNumber you can just write occur->lineNumber. ;-) Commented Dec 7, 2013 at 6:31
  • My first reaction looking at something like this is to think the OP is joking, but then I remember that a lot of people out there are writing code as if it were a series of incantations, without any understanding of what it means. Commented Dec 7, 2013 at 6:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.