Created
August 31, 2012 11:18
-
-
Save johnkawakami/3551598 to your computer and use it in GitHub Desktop.
Two examples of how to use GArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <glib.h> | |
| #include <stdio.h> | |
| int main( int argc, char *argv[] ) | |
| { | |
| GString *s; | |
| GString gs; | |
| GArray *a; | |
| int i; | |
| a = g_array_sized_new( FALSE, FALSE, sizeof(GString *), 100 ); | |
| for( i=0; i<100; i++ ) | |
| { | |
| s = g_string_new( "element" ); | |
| g_string_append_printf( s, ",%d", i ); | |
| g_array_append_val( a, s ); | |
| printf( "inserting %s\n", s->str ); | |
| } | |
| s = g_array_index( a, GString *, 40 ); | |
| printf( "retrieving %s\n", s->str ); | |
| } | |
| /* an alternative way is */ | |
| int main( int argc, char *argv[] ) | |
| { | |
| GString *s; | |
| GString gs; | |
| GArray *a; | |
| int i; | |
| a = g_array_sized_new( FALSE, FALSE, sizeof(GString), 100 ); | |
| for( i=0; i<100; i++ ) | |
| { | |
| s = g_string_new( "element" ); | |
| g_string_append_printf( s, ",%d", i ); | |
| g_array_append_val( a, *s ); | |
| printf( "inserting %s\n", s->str ); | |
| } | |
| gs = g_array_index( a, GString, 40 ); | |
| printf( "retrieving %s\n", gs.str ); | |
| } | |
| /* This second way is worse. There's more mental pointer math happening. */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment