GTK+ Forums Forum Index GTK+ Forums
Discussion forum for GTK+ and Programming. Ask questions, troubleshoot problems, view and post example code, or express your opinions.
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

question about g_list_index

 
Post new topic   Reply to topic    GTK+ Forums Forum Index -> GTK+ Programming
Author Message
Joel
GTK+ Guru


Joined: 06 Apr 2008
Posts: 225
Location: Fortress of solitude

PostPosted: Mon Mar 08, 2010 4:08 pm    Post subject: question about g_list_index Reply with quote

My list:
Code: (C)
1
2
3
4
5
6
7
8

GList *list = NULL;
list = g_list_append (list, "b1"); // 0
list = g_list_append (list, "b2"); // 1
list = g_list_append (list, "b3"); // 2
//...


The user needs to input either "b1", "b2", ... and later I need to get the position of that input.
Seems that reading the docs about "g_list_index", the last parameter needs to be "const" pointer, so using this:
Code: (C)
1
2
3
4

gint ret = scanf("%s", op); // if op == "b2"
gint pos = g_list_index(list,op); // pos should be 1

Doesn't work, returns -1...any alternative ideas?
Back to top
tadeboro
Never Seen the Sunlight


Joined: 23 Jul 2008
Posts: 2114
Location: Slovenia

PostPosted: Mon Mar 08, 2010 6:58 pm    Post subject: Reply with quote

Hi.

g_list_index() function directly compares pointers. If you want to retrieve list item with specific string, you'll probably need to use g_list_find_custom(). After you've obtained the list item with proper string, you can get it's index by calling g_list_position().

If you want to be more efficient, you can write down a loop like this that will replace g_list_find_custom() and g_list_position():

Code: (C)
1
2
3
4
5
6
7
8
9
10
11
12
13
GList *list,
      *iter;
gint   index;
gchar *search_term = "Some string";

/* Initialize your list here */

for( index = 0, iter = list; iter; index++, iter = g_list_next( iter ) )
    if( ! strcmp( iter->data, search_term ) )
        break;

/* Index now holds your desired item index */

Tadej
Back to top
Joel
GTK+ Guru


Joined: 06 Apr 2008
Posts: 225
Location: Fortress of solitude

PostPosted: Tue Mar 09, 2010 1:19 am    Post subject: Reply with quote

Thanks, that function helped..another question about the function:
Code: (C)
1
2
3
4
5
6
7
8
9
10
11

gint get_list_index (GList *list, const gchar *item)
{
     GList *iter = list; // is about "iter"
     
gint index = 0;
     for( ; iter; index++, iter = g_list_next( iter ) )
          if( ! g_strcmp0( iter->data, item ) )
               break;
     return index;
}

Does "iter" need to be free with g_list_free?
Back to top
Display posts from previous:   
Post new topic   Reply to topic    GTK+ Forums Forum Index -> GTK+ Programming All times are GMT
Page 1 of 1

 


Powered by phpBB © 2001, 2005 phpBB Group
CodeBB 1.0 Beta 2
Protected by Anti-Spam ACP