The measurement of the azimuthal-correlation function of prompt D mesons with charged particles in pp collisions at s=5.02TeV and p–Pb collisions at sNN=5.02TeV with the ALICE detector at the LHC is reported. The D , D +, and D ∗ + mesons, together with their charge conjugates, were reconstructed at midrapidity in the transverse momentum interval 3<pT<24GeV/c and correlated with charged particles having pT>0.3GeV/c and pseudorapidity | η| < 0.8. The properties of the correlation peaks appearing in the near- and away-side regions (for Δ φ≈ 0 and Δ φ≈ π, respectively) were extracted via a fit to the azimuthal correlation functions. The shape of the correlation functions and the near- and away-side peak features are found to be consistent in pp and p–Pb collisions, showing no modifications due to nuclear effects within uncertainties. The results are compared with predictions from Monte Carlo simulations performed with the PYTHIA, POWHEG+PYTHIA, HERWIG, and EPOS 3 event generators.