ToshioCP / Gtk4-tutorial

GTK 4 tutorial for beginners
https://toshiocp.github.io/Gtk4-tutorial/
548 stars 50 forks source link

Question about the struct pointer. #23

Closed qaqland closed 2 years ago

qaqland commented 2 years ago

What's the meaning of this line?

https://github.com/ToshioCP/Gtk4-tutorial/blob/ee6a19fe3ae212beeb458c2a17f9cc0f3b9ef39e/gfm/sec6.md?plain=1#L162

In my C learning, struct is define with {}. Maybe I'm too poor to understand it.

祝好/Best Wishes

ToshioCP commented 2 years ago

Thank you for the post to the issue. You are right and that is a wrong program. The correct program is:

char *s;
s = g_new (char, 10);
/* s points an array of char. The size of the array is 10. */

struct tuple {int x, y;} *t;
t = g_new (struct tuple, 5);
/* t points an array of struct tuple. */
/* The size of the array is 5. */

I made a sample program like this:

#include <stdio.h>
#include <gtk/gtk.h>

int
main(int argc, char **argv) {
  struct tuple {int x, y;} *t;
  t = g_new (struct tuple, 5);

  int i;
  for (i=0; i<5; ++i) {
    (t+i)->x = i;
    (t+i)->y = -i;
  }
  for (i=0; i<5; ++i) {
    printf ("i=%d, (x,y)=(%d,%d)\n", i, (t+i)->x, (t+i)->y);
  }
  g_free(t);
  return 0;
}

To compile this, type as follows.

$ gcc -Wl,--export-dynamic `pkg-config --cflags gtk4` t.c `pkg-config --libs gtk4`

I tried it and C compiler didn't display any error message. To run it:

$ ./a.out
i=0, (x,y)=(0,0)
i=1, (x,y)=(1,-1)
i=2, (x,y)=(2,-2)
i=3, (x,y)=(3,-3)
i=4, (x,y)=(4,-4)

I'll correct it as soon as possible. Thank you very much for your help.

Toshio

ToshioCP commented 2 years ago

The bug has been fixed.