tmighty
tmighty

Reputation: 11399

Pass vector as pointer

I have a vector of float

vector<float>nFloats;

I would like to pass it to the following function:

/* This is a non-stream oriented interface to just change the speed of a sound sample */
int sonicChangeFloatSpeed(
    float *samples,
    int numSamples,
    float speed,
    float pitch,
    float rate,
    float volume,
    int useChordPitch,
    int sampleRate,
    int numChannels)
{
    sonicStream stream = sonicCreateStream(sampleRate, numChannels);

    sonicSetSpeed(stream, speed);
    sonicSetPitch(stream, pitch);
    sonicSetRate(stream, rate);
    sonicSetVolume(stream, volume);
    sonicSetChordPitch(stream, useChordPitch);
    sonicWriteFloatToStream(stream, samples, numSamples);
    sonicFlushStream(stream);
    numSamples = sonicSamplesAvailable(stream);
    sonicReadFloatFromStream(stream, samples, numSamples);
    sonicDestroyStream(stream);
    return numSamples;
}

Can anybody tell me how to do it correctly?

My attempts

 1) int iRet = sonicChangeFloatSpeed(&nFloats[0], *num, 1, 0.5, 1, 1, 1, 48000, 1);

 2) int iRet = sonicChangeFloatSpeed(nFloats[0], *num, 1, 0.5, 1, 1, 1, 48000, 1);

 3) int iRet = sonicChangeFloatSpeed(*nFloats, *num, 1, 0.5, 1, 1, 1, 48000, 1);

all don't work.

I'm sure such a question has already been asked, but I couldn't find any exact duplicate.

Can anybody help?

Thank you.

Upvotes: 2

Views: 498

Answers (2)

4386427
4386427

Reputation: 44284

As far as I can tell, your approach is problematic.

Your function seems to do 2 things:

1) Write a number of floats to a stream

2) Read a number of floats from a stream

In both cases you want the floats to be in a vector.

For number 1 it is fine to use a vector but for number 2 it is very problematic.

You can't pass a pointer to the data held by a vector and then change the number of elements. The original vector will keep its original size. If you attempt to read more floats from the stream than currently held by the vector, the behavior is undefined.

Upvotes: 0

Shaana
Shaana

Reputation: 336

I think your first version should work, because the vectors use contiguous storage locations for their elements.

int iRet = sonicChangeFloatSpeed(&nFloats[0], nFloats.size(), 1, 0.5, 1, 1, 1, 48000, 1);

In c++11 you can use

float* p = nFloats.data();
int iRet = sonicChangeFloatSpeed(p, nFloats.size(), 1, 0.5, 1, 1, 1, 48000, 1);

Upvotes: 4

Related Questions