LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Inserting element to a list of list in C (http://www.linuxquestions.org/questions/programming-9/inserting-element-to-a-list-of-list-in-c-155269/)

suwandy_chandra 03-09-2004 12:52 AM

Inserting element to a list of list in C
 
I have a code which look like this,
Code:

    struct list1 {
        char *string;
        struct list1 *next;
    };
    struct list2 {
          struct list1 *first;
          struct list2 *next;
    };

and I wanted to use the second list in one my function, which is list_insert, which goes like
Code:

    struct list2 * list_insert (struct list2 *new, struct list1 *input) {
    struct list2 *temp;
 
        if (new == NULL) {
            new->first = input;  // ===> line of error
            new->next= NULL;
        }
        else {
            // some more codes
        }

However, as it turns out, after it compiles correctly, and I run it with one of my testcases, it gives me and error saying Bounds error : NULL or ILLEGAL pointer used in pointer arithmetic. I have malloc'ed the struct list2 *new in my main function. What's wrong with that? Do I have to malloc the struct list1 *first as well?

Any help will be very appreciated

cjcuk 03-09-2004 02:39 AM

Re: Inserting element to a list of list in C
 
Quote:

Originally posted by suwandy_chandra
Code:

    struct list2 * list_insert (struct list2 *new, struct list1 *input) {
    struct list2 *temp;
 
[1]      if (new == NULL) {
[2]          new->first = input;  // ===> line of error
[3]          new->next= NULL;
        }
        else {
            // some more codes
        }


It might be a coding error or a misunderstanding, but at [1] you are testing if `new' is NULL. If this returns a true value, then `new' is NULL and you cannot dereference and assign to it as you have done in [2] and [3]. The actual pointer arithmetic problem is because that is the way the structure dereferences are being calculated. My guess would be that you are not passing the structure you allocated to the function properly. There would not be an error in the case you have shown if `input' is NULL, as it would just be a NULL assignment which is acceptable -- however, you will need to allocate it somewhere if you want to use it ( though it does not have to be malloc(3), necessarily ).

One question, did you possibly mean to use `test' inside that block? If you did, that makes more sense. You will need to dynamically allocate it though, using malloc(3).

suwandy_chandra 03-09-2004 03:08 AM

Thanks, I found the error, which is as what you said.


All times are GMT -5. The time now is 11:38 AM.