title: How do you pass pointers/arrays as parameters to a GTK callback function?
body: <p>I want to pass a list of integers, <code>numbers</code> to a callback function <code>printer</code>, which will print the contents of <code>numbers</code> when a button is pressed. The last post in <a href="https://ubuntuforums.org/archive/index.php/t-1367759.html" rel="nofollow noreferrer">this</a> forum thread suggests that I do something like this:</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;gtk/gtk.h&gt;
  
  static void printer(GtkButton *button, gpointer user_data)
  {
      int *array = user_data;
      g_print(&quot;%d %d %d %d %d\n&quot;, array[0], array[1], array[2], array[3], array[4]);
  }
  
  static void activate(GtkApplication *app, gpointer user_data)
  {
      GtkWidget *win;
      GtkWidget *box;
      GtkWidget *button;
  
      // initialize numbers
      int numbers[5] = {2, 3, 5, 7, 11};
     
      // window
      win = gtk_application_window_new(GTK_APPLICATION(app));
      gtk_window_set_title(GTK_WINDOW(win), &quot;Printer&quot;);
      gtk_window_set_default_size(GTK_WINDOW(win), 80, 80);
      
      // box
      box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
      gtk_window_set_child(GTK_WINDOW(win), box);  
      
      // button
      button = gtk_button_new_with_label(&quot;Test&quot;);
      g_signal_connect(button, &quot;clicked&quot;, G_CALLBACK(printer), (gpointer) numbers);
      gtk_box_append(GTK_BOX(box), button);
  
      gtk_window_present(GTK_WINDOW(win));
  }
  
  int main (int argc, char **argv)
  {
      GtkApplication *app;
      int status;
      
      app = gtk_application_new(&quot;com.example.printer&quot;, G_APPLICATION_FLAGS_NONE);
      g_signal_connect(app, &quot;activate&quot;, G_CALLBACK(activate), NULL);
      status = g_application_run(G_APPLICATION(app), argc, argv);
      g_object_unref(app);
      
      return status;
  }
  </code></pre>
  <p>However, when I try to execute this, the program outputs:</p>
  <pre><code>0 0 0 32583 0
  </code></pre>
  <p>If the callback function modifies the contents of the array before it prints them, then the results printed will be correct:</p>
  <pre class="lang-c prettyprint-override"><code>static void printer(GtkButton *button, gpointer user_data)
  {
      int *array = user_data;
      array[0] = 3;
      array[1] = 2;
      array[2] = 1;
      array[3] = 0;
      array[4] = -1;
      g_print(&quot;%d %d %d %d %d\n&quot;, array[0], array[1], array[2], array[3], array[4]);
  }
  </code></pre>
  <p>This outputs <code>3 2 1 0 -1</code> as expected.</p>
  <p>I'm not sure why <code>array[x]</code> are different in both cases. Is this the recommended way for passing arrays into a callback function, and why does<code>array[x]</code> return different values in both cases?</p>