Home > Mobile >  Changing the variable assigned as a pointer to the parameter in C
Changing the variable assigned as a pointer to the parameter in C

Time:11-23

Firstly I'm using C language. I want a variable that I refer to as a parameter to change outside the function when it is changed inside the function. But the problem is that the variable is of type linked list and I want to add to the linked list.

So what I'm trying to do is add the linked list outside the function with the save function.

Is this possible? If possible how can I do it? Sorry for the English, I used a translator.

My codes:

#include <stdio.h>
#include <stdlib.h>

typedef struct NS
{
    char * name;
    char * value;
    struct NS * next;
} n_t;

void save(char * name, char * value, n_t ** item)
{
    n_t * link = malloc(sizeof(struct NS));
    link->name = name;
    link->value = value;
    link->next = NULL;
    
    n_t ** pointer = NULL;

    if (*item == NULL)
        *item = link;

    pointer = &(*item);

    while ((*pointer)->next != NULL)
        *pointer = (*pointer)->next;

    (*pointer)->next = link;
}

int main()
{

    n_t * mem = NULL;

    save("hello", "val123", &mem);

    printf("-> %s\n", mem->value);

    save("abc", "hello", &mem);

    printf("-> %s\n", mem->value);

    printf("-> %s\n", mem->next->value);

    return 0;
}

The output for the first arrow (->) should be "val123"

The result that should also appear in the second arrow output is "val123"

The result that should appear in the third arrow output is "hello"

CodePudding user response:

All this part of the function

n_t ** pointer = NULL;

if (*item == NULL)
    *item = link;

pointer = &(*item);

while ((*pointer)->next != NULL)
    *pointer = (*pointer)->next;

(*pointer)->next = link;

does not make sense. For example in the while loop

while ((*pointer)->next != NULL)
    *pointer = (*pointer)->next;

there is rewritten the value of the passed original pointer to the function by reference,

The function can look the following way

int  save( n_t **item, char *name, char *value )
{
    n_t * link = malloc( sizeof( struct NS ) );
    int success = link != NULL;

    if ( success )
    {
        link->name = name;
        link->value = value;
        link->next = NULL;

        while ( *item != NULL ) item = &( *item )->next;

        *item = link;
    }

    return success;
}

In general you need to dynamically allocated memory to store copies of the strings name and value in the nodes of the list.

The body of the function main can look like

n_t * mem = NULL;

save( &mem, "hello", "val123" );

printf("-> %s\n", mem->value);

save( &mem, "abc", "hello" );

printf("-> %s\n", mem->next->value );

printf("-> %s\n", mem->next->next->value);

CodePudding user response:

You're really only missing a single return when the list is empty still:

    if (*item == NULL) {
        *item = link;
        return;
    }
  • Related