Need help loading files with for loop into array with char*

Apr 7, 2011 at 4:23am
Hi,
Noob here.
I'm writing a simple random audio player and attempting to load all of my files into an array from which a file will be randomly selected. Here's my code:

1
2
3
4
5
6
7
8
9
10
11
void testApp::setup(){
      char* songNumber;
      for(int i = 100; i<295; i++)
    {

        sprintf(songNumber, "%03d.ogg", i);
        songArray[i].loadSound(songNumber);

    }
        songTrack();
}


I'm using openFrameworks libraries, hence the setup() and loadSound() functions. (songTrack() is the function that makes the random selection).

The problem I'm having is in loading the files in the first place. I continually get a segmentation fault. What am I doing wrong here? Is there a better way to do this?
Thanks!
Apr 7, 2011 at 5:43am
You need to allocate memory for your char array. However...why not just use an std::string?
Apr 8, 2011 at 3:06am
When I try std::string I get the message:
 
error: cannot convert 'std::string' to 'char*' for argument '1' to 'int sprintf(char*, const char* ...)'

This is totally over my head.
Apr 8, 2011 at 3:19am
You can't use sprintf() with std::strings, use an std::stringstream instead:

1
2
3
std::stringstream str;
str<<i<<".ogg";
songArray[i].loadSound(str.str());
Apr 8, 2011 at 3:58am
Thanks!
That's a much more elegant solution.
But I'm still getting a segmentation fault. Even when I only try to load one or two files.
What's causing this?
Apr 8, 2011 at 4:37am
Try setting a breakpoint and stepping through with your code with a debugger and see where it crashes. Once you find where, post the function and all related functions so we can look at it.
Topic archived. No new replies allowed.