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?
Asked
Active
Viewed 80 times
1
-
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 Answers
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
-
-
@noNAme If you like an answer, upvote it! If it solves your problem mark it as accepted ;) – Guillaume Racicot Nov 25 '21 at 18:14
-
-
@noNAme The question is now completely different than before. I would rollback it to its previous state and ask another question. – Guillaume Racicot Nov 25 '21 at 19:14
-
@noNAme This is not really how it works here. You cannot edit a question to ask something else. You have to ask a different one. My answer don't even apply to your problem anymore. The correct thing would be to rollback it to its previous state and ask another question with the new content. – Guillaume Racicot Nov 25 '21 at 20:27