1

I have a problem with the output of my program, the result should be encoding A to the binary system 01000001. My result is 10111110. Can you advise me what I am doing wrong or where I have an error?

noNAme
  • 15
  • 5
  • You can only find the length of an array passed to a function if a) there is another argument telling it, or b) there is a sentinel value as part of the data, such as with a string. The `[8]` you defined is ignored. An array passed to a function decays to a pointer to its first element and `sizeof` gives the size of that pointer. Anyway, `sizeof` would not give the number of elements, but the size in bytes (although they might be the same). – Weather Vane Nov 25 '21 at 18:04
  • The length information is not passed to the function, only the starting address of the array is. Hence you must add another mechanism. In your case, you hard-coded the length 8, so why not continue ? –  Nov 25 '21 at 18:05

1 Answers1

0

Since the array is a function argument, it behave the same as a pointer. This is how it works in C. In that case, sizeof don't get you the size of the whole array, but the size of a pointer.

Since your array has a fixed size, simply use that size:

void encode(const char character, bool bits[8]){
    int char_val = (int) character;
    int final_index = 8;

    for( int i = 0; i< 8; i++){
        // ..
    }
}

If you don't want to repeat yourself, in C you can define macros. The preprocessor will take care of doing the copy paste and not you:

#define BITS_SIZE 8
void encode(const char character, bool bits[BITS_SIZE]){
    int char_val = (int) character;
    int final_index = 8;

    for( int i = 0; i< BITS_SIZE; i++){
        // ..
    }
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141