Search code examples
cfunctionpointersargument-passingglib

passing glist pointer as argument to reflect changes in list does not work


I want to pass the glist pointer to the function so that I can get the changed value in main function.

I have code as:

#include <stdio.h>
#include <string.h>
#include <glib.h>

char *col_trim_whitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}


void line_parser(char *str,GSList* list1)
{
    GSList* list = NULL; 
    char *token, *remstr=NULL ;

    token = strtok_r(str,"\n",&remstr);
    while(token != NULL)
        {
            if(token[0] == ' ')
            {

            token = col_trim_whitespace(token);
            if(strcmp(token,"")==0)
                 {
                     token = strtok_r(NULL, "\n", &remstr);
                     continue;
                  }
            }
            list1 = g_slist_append(list1, token);
            token = strtok_r(NULL,"\n",&remstr);
        }

}

int main()
{

 int *av,i,j,length;
 i=0;

char str[] = " this name of \n the pet is the ffffffffffffffffffffffffffffff\n is \n the \n test\n program";


//GSList *list1 = line_parser(str);
GSList *list1 = NULL;
line_parser(str,list1 );
// printf("The list is now %d items long\n", g_slist_length(list));
 length = g_slist_length(list1);
// printf("length=%d", length);

for(j=0;j<length;j++)
{
    printf("string = %s\n",(char *)g_slist_nth(list1,j)->data);
}

g_slist_free(list1);

return 0;
}

here I have a list name list1 in the main function, then I passed list1 as an argument to the lineparser() function where the list is changed appending some values. and I want to return the value to the main() function but without using a return statement as I have used the pointer reference while passing argument. but the value is not returned to the main() function. How can I achieve this?


Solution

  • Seems you want to pass the address of the list pointer, and then have the parser update that variable:

    void line_parser(char *str,GSList **list1)
    {
        ...
        *list1= list;
    }
    

    and in main:

    main()
    {
        GSList *list1 = NULL;
        line_parser(str, &list1);
        ...
    }