Home > Enterprise >  printf in C: Speicherzugriffsfehler (Speicherabzug geschrieben) core dumped
printf in C: Speicherzugriffsfehler (Speicherabzug geschrieben) core dumped

Time:11-06

struct node {
    int key;
    char value[32];
    struct node *next;
};

struct node *list = NULL;

struct node *add(struct node *list, int key, char *value){
    struct node *n = malloc(sizeof(struct node));
    n->key = key;
    strcpy(n->value, value);
    n->next = list;
    return n;
}

struct node *get(struct node *list, int key){

    struct node *n = list;
    while((n != NULL) && (n->key != key)){
        n = n->next;
    }
    return (n != NULL && n->key == key) ? n : NULL;
}


int main(void) {

    list = add(list, 3000, "Bern");
    list = add(list, 4000, "Basel");
    list = add(list, 8000, "Zurich");

    while (list != NULL) {
         printf("Node %s mit Key %d\n", list->value, list->key);
         list = list->next;
    }

    struct node *n = get(list, 4000);
    printf("Key is: %d \n", n->key);

}

I would like to get a pointer to struct node if it can be found in the list. In the code below, I try to print the key of a node (last line in the code), which is in the list, but I get an error. Can someone please help me?

CodePudding user response:

After this while loop

while (list != NULL) {
     printf("Node %s mit Key %d\n", list->value, list->key);
     list = list->next;
}

the pointer list is equal to NULL. So you may not use it any more to access nodes of the list.

You need to use an intermediate pointer as for example

for ( const struct node *current = list; current != NULL; current = current->next ) 
{
    printf("Node %s mit Key %d\n", current->value, current->key);
}

Pay attention to that this return statement

return (n != NULL && n->key == key) ? n : NULL;

can look much simpler as

return n;

And will be more safer to write

struct node *n = get(list, 4000);
if ( n ) printf("Key is: %d \n", n->key);

CodePudding user response:

Awesome! Thanks so much for your help. :)

  • Related