Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Method to fill histograms

  1. Jul 25, 2008 #1


    User Avatar

    Basically I've made a method to fill histograms and I need to use sprintf to define histogram titles with a wildcard (%s) that I call to be a string such as proton, antiproton etc depending on what dat I want to plot.

    So anyway, here's an example of what I've done:

    void PythiaMC_Analysis::fillMM_Histos(string histoID, double deltaPseudo) {

    char histo1_name[100];


    Which I'd call after defining the histoID to be proton, antiproton or whatever. I've simplified the code to one plot for the sake of brevity.

    SO basically I'm getting segmentation violations to do with this method, I have deduced that it occurs at the first occurance of sprintf. Am I using it incorrectly?

    Any help would be much appreciated.
  2. jcsd
  3. Jul 25, 2008 #2


    User Avatar
    Science Advisor
    Homework Helper

    Re: sprintf

    You should set at least the first element of histo1_name[] to 0, otherwise it is likely to be created full of random data (at least in a release build), a \0 is needed to mark the end of a C string.

    Also sprintf is a c function, the %s matches a 'C' \0 terminated string, it doesn't know anything about the c++ string data type you are using.
    Your string library probably has a getData method or can automatically convert it with something like (char*)histoID.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Threads - Method fill histograms Date
C/++/# Typically where are preconditions checked for methods? Jan 22, 2018
What's wrong with my bisection method code? Dec 10, 2017
C/++/# Question about a specific class method in C++ Nov 7, 2017
Why are matrix methods so widely used? May 16, 2017
C/++/# 3d space filling tree Apr 5, 2017