Skip to content

Instantly share code, notes, and snippets.

@johnkawakami
Created August 31, 2012 11:18
Show Gist options
  • Save johnkawakami/3551598 to your computer and use it in GitHub Desktop.
Save johnkawakami/3551598 to your computer and use it in GitHub Desktop.
Two examples of how to use GArray
#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