Problem with linked lists

I am working on a problem for which I need to use a linked list of a sort. For this particular application I need each node to refer to a set of other nodes.
A simplified version of the code looks as follows:

#include <stdio.h>
#include <stdlib.h>

struct record {
  int id;
  struct record **friends;
};

int main(){
    int i;
    struct record *data;

/* This uncommented piece of code works as it is supposed to */
//  data=malloc(3*sizeof(struct record));
//  data[0].friends=malloc(2*sizeof(struct record));    
//  for(i=0;i<3;i++) data.id=i;
//  data[0].friends[0]=&data[1];
//  printf("%d %d\n", data[0].id, data[0].friends[0]->id);  

    subroutine(&data);
}

void subroutine(struct record **data){
    int i;
    
/* This piece of code produces a wrong output */
    *data=malloc(3*sizeof(struct record));
    (*data)[0].friends=malloc(2*sizeof(struct record));
    for(i=0;i<3;i++) (*data).id=i;
    (*data)[0].friends[0]=data[1];
    printf("%d %d\n", (*data)[0].id, (*data)[0].friends[0]->id);  
}

A successful run results in the printing of "0 1". The uncommented code in main() gives the correct result, but if I pass the data to the subroutine, I get something weird. Can anybody help me?

This line is dodgy:

data[0].friends=malloc(2*sizeof(struct record));

record::friends is of type pointer to pointer to struct record, but you are allocating space for two structs, which isn't the same thing. You need friends to point to the memory you allocated.
Try this

#include <stdio.h>
#include <stdlib.h>

struct record {
  int id;
  struct record **friends;
};

void subroutine(struct record **data){
    int i;
    *data=malloc(3*sizeof **data);
    struct record* friends = malloc(2*sizeof *friends);
    (*data)[0].friends=&friends;
    for(i=0;i<3;i++) (*data).id=i;
    (*data)[0].friends[0]=data[1];
    printf("%d %d\n", (*data)[0].id, (*data)[0].friends[0]->id);
}

int main(){
    int i;
    struct record *data;

/* This uncommented piece of code works as it is supposed to */
  data=malloc(3*sizeof *data);
  struct record* friends = malloc(2*sizeof *friends);
  data[0].friends=&friends;
  for(i=0;i<3;i++) data.id=i;
  data[0].friends[0]=&data[1];
  printf("%d %d\n", data[0].id, data[0].friends[0]->id);

  struct record *data1;
  subroutine(&data1);
  return EXIT_SUCCESS;
}