i'm having problems appending data to the end of a dynamic array, i'm reading in data from a wave file and then getting the number of frames and creating a dynamic array with that memory size however in my loop the data doesn't appear to add to the array, here is a sample, any ideas what might be going wrong? (i should note, i've been doing python for a little while and this is my first jump into the world of c+ and i miss some of the list methods )
buf = (int *) malloc(num_items*sizeof(int));
num = sf_read_int(sf,buf,num_items);
sf_close(sf);
rawWaveDataArray = new int[num_items];
int arraySize = sizeof(rawWaveDataArray);
printf("the array size is: %d \n", arraySize);
printf("Read %d items\n", num);
/* Write the data to filedata.out. */
out = fopen("filedata.out","w");
for (i = 0; i < num; i += c)
{
for (j = 0; j < c; ++j)
Re: problems appending to array (dynamic array size)
Originally Posted by dommmm
any ideas what might be going wrong?
The thing you're doing "wrong" is that you are using 'C' memory allocation routines instead of the various ready-made standard container classes that are part of the C++ library.
Re: problems appending to array (dynamic array size)
thanks! that worked kinda. i'm getting some kind of out of bounds error at runtime now though:
/Developer/SDKs/MacOSX10.5.sdk/usr/include/c++/4.0.0/debug/vector:192:
error: attempt to subscript container with out-of-bounds index 1757448,
but container only holds 1757448 elements.
I integrated the code you put and it looks like this:
vector <int> rawWaveDataArray;
out = fopen("filedata.out","w");
for (i = 0; i < num; i += c)
{
for (j = 0; j < c; ++j)
I'm guessing by the error message that this is because the vector is being accessed by one container too many, but I was under the impression that vectors scale automatically unlike arrays.
Re: problems appending to array (dynamic array size)
Originally Posted by dommmm
but I was under the impression that vectors scale automatically unlike arrays.
They do not resize themselves -- you have to resize the vector using the various methods, namely:
1) push_back()
2) resize()
3) insert()
4) erase()
5) clear()
6) on construction of the vector, you size it there.
You cannot resize a vector by using operator []. If you go beyond the boundaries of your vector, then the behaviour is undefined.
As an alternative, if you use vector::at() instead of [], the at() will throw an exception if you attempt to use the vector beyond its boundaries. Then you will know exactly where you are going over the edge.
Bookmarks