problem printing a vector with a loop

why am i getting a seg fault from this code??
1
2
3
  bit_vector decoded_lcw_vec(corrected_array, corrected_array + sizeof corrected_array / sizeof corrected_array[0]) ; 
    printf( "\n Decoded LCW Vector:");
    for(int i = 0 ; i < 96; i++ )  printf("%c", decoded_lcw_vec[i]) ;    

when i comment out the print loop there is no seg fault.
If you try to access an index in a vector that doesn't exist you get a seg fault. In this loop you are trying to access every index in the vector all the way up to 95. However, your vector probably doesn't have enough values to fill all that up, so you get seg faults when the program reads pieces of the vector that don't exist.

To fix this, you need to let the loop know how many indices are in the vector using the size() member function.

for (int i = 0; i < decoded_lcw_vec.size(); ++i) ...
this how the vector is filled:
1
2
3
4
5
6
7
8
9
10
11
int corrected_array[96] = {0};  
    for ( i=0; i<16; i++) //error corrected "hex-bits" back to binary
    {
        for ( j = 0; j<6; j++)
        {
            int mask = 1 << (5 - j);
            corrected_array[i*6 + j] = ((recd[8+i] & mask) != 0);
        }
    }

bit_vector decoded_lcw_vec(corrected_array, corrected_array + sizeof corrected_array / sizeof corrected_array[0]) ; 

Would there not be 95 values in the vector? the corrected_array is typed int and the vector is typed bool. am i filling this vector incorrectly? Thanks!

Last edited on
Okay, you have 95 indices, but there are a lot of holes in the vector that it is stumbling on.

For example, when i is 1 and j is 1... i*6 + j = 7. So, even at the beginning, the vector starts at the 7th index. 0-6 are non-existent and it is stumbling on that.

So the problem is originating in your corrected_array[i*6 + j].
what about when i =0 and j = 0 ? if i do a :
 
for(i=0; i<96; i++) printf("%d", corrected_array[i]);

then the correct 96 bits will be printed. so i am confused as to how the array has empty positions ??
Okay, I just went through the first large bit of the loop and I was mistaken. There aren't any empty positions.

Try changing the "%c" in the printf statement to a "%i". See if that helps.
using cout instead of printf() gets the data on the screen.
Topic archived. No new replies allowed.