Here is a example of how to do it using getgrouplist, feel free to ask anything.
__uid_t uid = getuid();//you can change this to be the uid that you want
struct passwd* pw = getpwuid(uid);
if(pw == NULL){
perror("getpwuid error: ");
}
int ngroups = 0;
//this call is just to get the correct ngroups
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
__gid_t groups[ngroups];
//here we actually get the groups
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
//example to print the groups name
for (int i = 0; i < ngroups; i++){
struct group* gr = getgrgid(groups[i]);
if(gr == NULL){
perror("getgrgid error: ");
}
printf("%s\n",gr->gr_name);
}