Device-to-device (D2D) communication underlaying cellular networks enhances system capacity through using spectrum resources of idle cellular users, which at the same time can act as relays to form cooperative D2D transmissions. On the other hand, network coding increases the efficiency of relay cooperation. In this letter, we investigate the random linear network coding aided D2D communications by addressing the problem of joint resource allocation and relay selection among multiple idle cellular users and D2D pairs. By formulating it as a binary integer non-linear programming problem, we obtain the optimal solution by introducing the concept of D2D cluster. Extensive simulations demonstrate that our proposed scheme increases the system sum rate by about 50% on average, while guaranteeing the minimum required rate of D2D pair.