I'm currently reading in a list of words from a file and trying to sort them line by line.
I can read each line in and print the words out just fine, but I can't seem to sort each line individually. The first line is sorted, but the second is not. Can anyone see where I'm going wrong? Thanks!
int fd;
int n_char = 0;
int charCount = 0, wordCount = 0, lineCount = 0;
int wordsPerLine[100];
char buffer;
char words[6][9];
fd = open(inputfile, O_RDONLY);
if (fd == -1) {
exit(1);
}
wordsPerLine[0] = 0;
/* use the read system call to obtain 10 characters from fd */
while( (n_char = read(fd, &buffer, sizeof(char))) != 0) {
if (buffer == '\n' || buffer == ' ') {
words[wordCount][charCount] = '\0';
charCount = 0;
wordCount++;
wordsPerLine[lineCount] += 1;
if (buffer == '\n') {
lineCount++;
wordsPerLine[lineCount] = 0;
}
} else {
words[wordCount][charCount++] = buffer;
}
}
printf("Num Words: %d --- Num Lines: %d\n", wordCount, lineCount);
char tmp[9];
int m, n;
int i, x, totalCount = 0;
for (i = 0; i < lineCount; i++) {
for (x = 0; x < wordsPerLine[i]; x++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = 0; n < wordsPerLine[i]; n++) {
if(strcmp(words[n-1], words[n])>0) {
strcpy(tmp, words[n-1]);
strcpy(words[n-1], words[n]);
strcpy(words[n], tmp);
}
}
} /* end sorting */
}
}
printf("Sorted:\n");
totalCount = 0;
for(i = 0; i < lineCount; i++) {
printf("Line %d (%d words)\n", i + 1, wordsPerLine[i]);
for(x = 0; x < wordsPerLine[i]; x++) {
printf("%s\n", words[totalCount++]);
}
}
My sample input file is:
great day out
foo bar food
Let's go by small parts...
To see if the problem is in the reading, comment the reading part and try to add:
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
and set the counters to the value they would with this input also...
Your loop is accessing some data out of the bounds... I would recommend you to try your sorting code with an array of numbers first and see if it is sorting them correctly...
#include<stdio.h>
#define N 6
int main()
{
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
int numbers[] = {20, 10, 50, 5, 30, -50};
int i, j, temp;
for(i = 0; i < N - 1; i++)
for(j = 0; j < N - 1; j++)
if(numbers[j] > numbers[j + 1])
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
for(i = 0; i < N; i++)
{
printf("%d\n", numbers[i]);
//printf("%s\n", words[i]);
}
}
Note also that this is the least efficient implementation of bubble sort (but is the same you provided), you can improve it by adding a variable to check in the inner loop some change happened for instance(which would mean that it is already sorted and you can stop sorting)...
Also, after each iteration on the outter loop one element is going to be placed in its final place (try to find out which one), which means that you won't need to consider this element in the next iteration, so after each iteration in the outer loop the number of elements compared in the inner loop can be reduced by 1...
you can find more info about bubble sort here
/* iterate through each line */
for (i = 0; i < lineCount; i++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = m+1; n < wordsPerLine[i]; n++) {
if(strcmp(words[n + totalCount], words[m + totalCount]) < 0) {
strcpy(tmp, words[m + totalCount]);
strcpy(words[m + totalCount], words[n + totalCount]);
strcpy(words[n + totalCount], tmp);
}
}
} /* end sorting */
totalCount += wordsPerLine[i];
}
I just needed to keep a running count of each word per line, so i know what line to start comparing with
Related
I had a task and the program is working, for the most part, however, it crashes if I put SPLIT value between 4 and 7 (crashes at different values, if I change SIZE, but for sake of simplicity, let's keep it at 10).
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#define SIZE 10
#define SPLIT 4
#define LOW 0
#define HIGH 10
void generateArray(int data[],int size,int low, int high){
srand(time(NULL));
for(int i=0;i<size;++i){
data[i]=rand()%(high-low+1)+low;
}
}
int splitData(int arraySize, int startArray[], int splitPoint, int **firstNewArray, int **secondNewArray){
if(arraySize < 1){
return -1;
}
if(splitPoint < 1 || (splitPoint >= arraySize)){
return -1;
}
if(*firstNewArray != NULL || *secondNewArray != NULL){
return -1;
}
*firstNewArray = malloc(splitPoint * sizeof(int));
*secondNewArray = malloc((arraySize - splitPoint) * sizeof(int));
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
(*firstNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}else{
(*secondNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}
}
return 0;
}
int main(){
int arraySize = SIZE ;
int *startArray = malloc(arraySize * sizeof(int));
generateArray(startArray,arraySize,LOW,HIGH);
int splitPoint = SPLIT;
int *firstNewArray = NULL;
int *secondNewArray = NULL;
int result;
result = splitData(arraySize, startArray, splitPoint, &firstNewArray, &secondNewArray);
if(result == 0){
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
printf("First array number %d is %d\n",i+1,firstNewArray[i]);
}else{
printf("Second array number %d is %d\n",i,secondNewArray[i]);
}
}
free(firstNewArray);
free(secondNewArray);
}
free(startArray);
return 0;
}
What could be the cause of this behavior and how could I fix it? The task is to split startArray by the value SPLIT into 2 new dynamic arrays, that would be created in a function splitData and both of them could be used outside the function.
You have two issues with your code
first when you display the results:
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
printf("First array number %d is %d\n",i+1,firstNewArray[i]);
}else{
printf("Second array number %d is %d\n",i,secondNewArray[i]);
}
}
This will not work specialy if array size is too higth or too low, example splitPoint is 9, this means secondNewArray Size is 1 but in this loop you are accessing secondNewArray[9] where it should be 0, you need to change the loop into something like this
for(int i = 0; i < splitPoint; ++i){
printf("First array number %d is %d\n",i+1,firstNewArray[i]);
}
for(int i = 0; i < SIZE - splitPoint; ++i){
printf("Second array number %d is %d\n",i+splitPoint+1 ,secondNewArray[i]);
}
You have the same isssue in your split function:
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
(*firstNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}else{
(*secondNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}
}
In this case also you are accessing regions outside the size of your array, let say split is 9 you will be accessing secondNewArray[9] = startArray[9] where it should be secondNewArray[0] = startArray[9], to fix this you need to do the same thing here where you use different index for each array, the code should look like this:
int j = 0;
int k = 0;
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint) {
(*firstNewArray)[j] = startArray[i];
printf("%d\n",startArray[i]);
j++;
}
else {
(*secondNewArray)[k] = startArray[i];
printf("%d\n",startArray[i]);
k++;
}
}
Take a hard look at the marked line below
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
(*firstNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}else{
(*secondNewArray)[i] = startArray[i]; // LOOK HERE
printf("%d\n",startArray[i]);
}
Assuming an array size of 10 and a split point of 4, then *secondNewArray is indexed from 0 to 5; however, you’re trying to assign elements 4 through 9, which is outside the bounds of the array, leading to undefined behavior. You need to adjust the value of i in order to map properly:
(*secondNewArray)[i - splitPoint] = startArray[i];
Task description -> Whole task description is here
I have done part with sorting and got stuck.
How can I combine these arrays in one of already sorted pairs?
printf("\nHeight of boys in descending order\n");
for (i = (LENGTH1 - 1); i >= 0; i--)
{
printf("%d ", heightBoys[i]);
}
for (i = 0; i < LENGTH2; i++)
{
for (j = 0; j < (LENGTH2 - j - 1); j++)
{
if (heightGirls[j] > heightGirls[j+1])
{
temp = heightGirls[j];
heightGirls[j] = heightGirls[j+1];
heightGirls[j+1] = temp;
}
}
}
printf("\nHeight of girls in descending order\n");
for (j = (LENGTH2 - 1); j >= 0; j--)
{
printf("%d ", heightGirls[j]);
}
You have a sort [for the girls], but it is broken. Change:
for (j = 0; j < (LENGTH2 - j - 1); j++)
Into:
for (j = 0; j < (LENGTH2 - i - 1); j++)
To avoid [needless] replication of code, put the sorting code into a separate function.
Sort both arrays.
Take the minimum of the lengths of the two arrays (e.g. minlen).
I'm not sure what you mean [exactly] by "pairing", but the simplest is to print the pairing
Then, just loop on:
for (i = 0; i < minlen; ++i)
printf("Girl:%d Boy:%d\n",heightGirls[i],heightBoys[i]);
If you needed something more complex, you might need an array of structs like:
struct pair {
int boyheight;
int girlheight;
};
This array would need to be at least minlen in length. You could fill it in by adapting the final print loop.
But, if you're just printing, here is some sample code:
#include <stdio.h>
void
print_single(const int *height,int len,const char *sex)
{
printf("\nHeight of %s in descending order\n",sex);
for (int i = (len - 1); i >= 0; i--)
printf(" %d", height[i]);
printf("\n");
}
void
sort_height(int *height,int len)
{
for (int i = 0; i < len; i++) {
for (int j = 0; j < (len - i - 1); j++) {
if (height[j] > height[j + 1]) {
int temp = height[j];
height[j] = height[j + 1];
height[j + 1] = temp;
}
}
}
}
int
main(void)
{
int heightBoys[] = { 5, 8, 7, 9, 6 };
int heightGirls[] = { 3, 1, 2 };
int LENGTH1 = sizeof(heightBoys) / sizeof(heightBoys[0]);
int LENGTH2 = sizeof(heightGirls) / sizeof(heightGirls[0]);
sort_height(heightBoys,LENGTH1);
print_single(heightBoys,LENGTH1,"boys");
sort_height(heightGirls,LENGTH2);
print_single(heightGirls,LENGTH2,"girls");
int minlen = LENGTH1;
if (minlen > LENGTH2)
minlen = LENGTH2;
printf("\n");
printf("Pairing:\n");
for (int i = 0; i < minlen; ++i)
printf("Girl:%d Boy:%d\n",heightGirls[i],heightBoys[i]);
return 0;
}
UPDATE:
Let's say that we input heights and number of them by ourselves. If we have extra heights of boys or girls, how can we output these extra heights apart from the rest?
Two additional for loops appended to the bottom should do the trick. In order for this to work, the iteration variable of the final for loop in the previous example must be defined outside the loop. In other words, notice the definition and usage of ipair below.
If you are creating an array the type of struct that I suggested, these loops can fill it in. The array size would then need to be max(LENGTH1,LENGTH2).
And, in unpaired loops (e.g. for boy 8, the girl value in the struct could be set to 0 or -1 to indicate that the boy is unpaired)
#include <stdio.h>
void
print_single(const int *height,int len,const char *sex)
{
printf("\nHeight of %s in descending order\n",sex);
for (int i = (len - 1); i >= 0; i--)
printf(" %d", height[i]);
printf("\n");
}
void
sort_height(int *height,int len)
{
for (int i = 0; i < len; i++) {
for (int j = 0; j < (len - i - 1); j++) {
if (height[j] > height[j + 1]) {
int temp = height[j];
height[j] = height[j + 1];
height[j + 1] = temp;
}
}
}
}
int
main(void)
{
int heightBoys[] = { 5, 8, 7, 9, 6 };
int heightGirls[] = { 3, 1, 2 };
int LENGTH1 = sizeof(heightBoys) / sizeof(heightBoys[0]);
int LENGTH2 = sizeof(heightGirls) / sizeof(heightGirls[0]);
sort_height(heightBoys,LENGTH1);
print_single(heightBoys,LENGTH1,"boys");
sort_height(heightGirls,LENGTH2);
print_single(heightGirls,LENGTH2,"girls");
int minlen = LENGTH1;
if (minlen > LENGTH2)
minlen = LENGTH2;
int ipair = 0;
printf("\n");
printf("Pairing:\n");
for (; ipair < minlen; ++ipair)
printf("Girl:%d Boy:%d\n",heightGirls[ipair],heightBoys[ipair]);
if (ipair < LENGTH1) {
printf("\n");
printf("Unpaired Boys:\n");
for (int i = ipair; i < LENGTH1; ++i)
printf("Boy:%d\n",heightBoys[i]);
}
if (ipair < LENGTH2) {
printf("\n");
printf("Unpaired Girls:\n");
for (int i = ipair; i < LENGTH2; ++i)
printf("Girl:%d\n",heightGirls[i]);
}
return 0;
}
I'am trying to write a program for converting the given string in cross manner(i.e Diagonal from left-right and from right-left). If the string length is even it returns a message else arrange it in a cross form.
The code is:
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char str2[50][50];
int lenstr;
int i,j;
char temp;
printf("Enter the string :\n");
scanf("%s",str);
lenstr = strlen(str);
if(lenstr %2 == 0)
{
printf("The string length must be an odd length");
}
else
{
j = 0;
temp = 0;
for(i = 0;i == lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = lenstr; i==0 ;i--)
{
j = lenstr;
str2[i][j] = str[temp];
temp = temp + 1;
j = j - 1;
}
for(i = 0;i<lenstr;i++)
{
for(j = 0;j<lenstr;j++)
{
printf("%c",str2[i][j]);
}
printf("\n");
}
}
return 0;
}
The output to the program must be for example: geeks
g g
e e
e
k k
s s
But the output obtained consists of different shapes(like heart,smiley face etc...). Explain the concept behind to correct it and if can please explain when using pointers for the same program. Any help appreciated.
In your code, you need to change the for loop condition checking expressions, like i == lenstr and later i==0. They are not entering the loop, essentially.
Instead, you can replace the whole block
for(i = 0;i == lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = lenstr; i==0 ;i--)
{
j = lenstr;
str2[i][j] = str[temp];
temp = temp + 1;
j = j - 1;
}
in your code by
for(i = 0;i<lenstr;i++)
for(j = 0;j<lenstr;j++)
str2[i][j] = ' '; //fill 2D array with space
for(i = 0;i < lenstr;i++)
{
str2[i][i] = str[i]; //set the character
str2[i][lenstr- i -1] = str[i]; //reverse position
}
and get the desired output.
See it LIVE.
Your logic to store diagonal string seems to be wrong. In the first loop you store left-right diagonal and your index goes from 0 to length-1 and your column starts from 0; increment it by 1. Its same for right-left diagonal, only difference being column starts from length-1 and ends at 0. Hence you need to initialize temp = lenstr -1;
temp = lenstr -1;
for(i = 0;i <lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = 0;i <lenstr;i++)
{
str2[i][temp] = str[i];
temp = temp - 1;
}
I think the problem is that str2 is not getting initialized. The first two for loops should be something like
for(i = 0;i < lenstr;i++)
and
for(i = lenstr; i>=0 ;i--)
Here is my five cents. The program allows to enter words with an odd or even number of letters.
Enjoy!:)
#include <stdio.h>
#include <string.h>
#define N 25
int main(void)
{
while ( 1 )
{
char s[N];
printf( "Enter a string less than %zu characters (Enter-exit): ", N );
if ( !fgets( s, N, stdin ) || s[0] == '\n' ) break;
size_t n = strlen( s );
if ( s[n-1] == '\n' ) s[--n] = '\0';
printf( "\n" );
for ( size_t i = 1, j = n; i <= n; i++, j-- )
{
char c = s[i-1];
if ( i < j ) printf( "%*c%*c\n", i, c, j - i, c );
else if ( j < i ) printf( "%*c%*c\n", j, c, i - j, c );
else printf( "%*c\n", i, c );
}
}
return 0;
}
If to enter
Stackoverflow
hello
then the program output will be
Enter a string less than 25 characters (Enter-exit): Stackoverflow
S S
t t
a a
c c
k k
o o
v
e e
r r
f f
l l
o o
w w
Enter a string less than 25 characters (Enter-exit): hello
h h
e e
l
l l
o o
Enter a string less than 25 characters (Enter-exit):
import java.util.*;
public class CrossCharacter {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.next();
int len = str.length();
char[][] ch_matrix = new char[len][len];
len--;
for(int i=0;i<=len;i++)
ch_matrix[i][i] = ch_matrix[i][len-i] = str.charAt(i);
for(int i=0;i<=len;i++){
for(int j=0;j<=len;j++)
System.out.print(ch_matrix[i][j]);
System.out.println();
}
}
}
# include<stdio.h>
void main() {
char n[100],temp;
int i = 0, j;
scanf("%s", &n);
m = strlen(n);
for(i = 0; i <= m - 1;)
temp[i];
i++;
for(j = 0; j < m - 1; j++)
{
if(i == j + 1 || j == m - 1 - i + 1)
printf("%c",temp);
else
printf(" "):
}
printf("\n");
getch();
}
i am writing a rail fence cipher algorithm in c for fun and to brush up on my C programming skills. i have it working well for smallish input phrases, but it gets garbled for some reason when the input phrase is large.
here is the code: (sorry, i couldnt reduce it to a SSCCE, i dont know which part of the algorithm is causing the problem)
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
/* function to append a char to a char array */
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int main(void)
{
int num_rails;
for (num_rails = 2; num_rails < 6; num_rails++)
{
char* message = "therailfencecipheristrickyespeciallywhentheinputisverylongabcdefghijklmnopqrstuvwxyzblerpblorp";
int word_len = strlen(message);
char* lines[num_rails];
char* rails[num_rails];
int len_rails[num_rails];
memset(len_rails, 0, num_rails*sizeof(int));
int i,j,k,mod;
int repeats;
int period = (2*num_rails) - 2;
printf("%d characters, %d rails:\n", word_len, num_rails);
printf("\nplaintext: %s\n", message);
/* encryption */
for (i = 0; i < num_rails; i++)
{
if ((lines[i] = malloc(sizeof(char))) == NULL)
{
printf("\nUnable to allocate memory.\n");
return EXIT_FAILURE;
}
}
for (repeats = 0; repeats < ((word_len/period)+1); repeats++)
{
if (repeats*period < word_len)
append(lines[0], message[repeats*period]);
for (j = 1; j < period/2; j++)
{
if ((j + (repeats*period)) < word_len)
append(lines[j], message[j + (repeats*period)]);
if ((((repeats+1)*period) - j) < word_len)
append(lines[j], message[((repeats+1)*period) - j]);
}
if (((period/2) + (repeats*period)) < word_len)
append(lines[j], message[(period/2)+(repeats*period)]);
}
char encrypted[word_len];
strcpy(encrypted,lines[0]);
for (i = 1; i < num_rails; i++)
strcat(encrypted, lines[i]);
printf("\nciphertext: %s\n", encrypted);
/* decryption */
for (i = 0; i < num_rails; i++)
{
if ((rails[i] = malloc(sizeof(int) * 40)) == NULL)
{
printf("\nUnable to allocate memory.\n");
return EXIT_FAILURE;
}
}
mod = word_len % period;
len_rails[0] = word_len / period;
len_rails[num_rails-1] = len_rails[0];
for (i = 1; i < num_rails - 1; i++)
len_rails[i] = len_rails[0] * 2;
for (i = 0; i < mod && i < num_rails; i++)
{
len_rails[i]++;
}
for (j = i-2; i < mod && j > -1; j--)
{
len_rails[j]++;
i++;
}
printf("\nrail lengths:");
for (i = 0; i < num_rails; i++)
printf(" %d", len_rails[i]);
putchar('\n');
k = 0;
for (i = 0; i < num_rails; i++)
{
for (j = 0; j < len_rails[i]; j++)
{
append(rails[i], encrypted[k++]);
}
}
char deciphered[word_len];
strcpy(deciphered, "");
for (i = 0; i < ((word_len/period)+1); i++)
{
if (rails[0][i])
append(deciphered, rails[0][i]);
for (j = 1; j < num_rails-1; j++)
{
if (rails[j][i*2])
append(deciphered, rails[j][i*2]);
}
if (rails[num_rails-1][i])
append(deciphered, rails[num_rails-1][i]);
for (j = num_rails-2; j > 0; j--)
{
if (rails[j][(i*2)+1])
append(deciphered, rails[j][(i*2)+1]);
}
}
printf("\ndeciphered: %s\n", deciphered);
printf("==========================================\n");
}
}
it should compile and run fine so you can test it.
it is supposed to print the plain text, then encipher it and print that, then decipher the enciphered text back to plain text and print that for 2, 3, 4, 5 rails but it should work for any number of rails.
the problem is that the output gets garbled if the input variable "message" gets over a certain size for different numbers of rails.
eg.
2 rails becomes garbled at 63 characters
3 rails becomes garbled at 64 characters
4 rails becomes garbled at 95 characters
5 rails becomes garbled at 126 characters
etc.
the closest i have been able to come to working out what is wrong is that whenever any value for len_rails[] exceeds 31 the output gets garbled for that amount of rails..
does anyone have any idea why this would be? is it to do with how i am allocating memory? its been a while since i did any C programming and my memory handling is a bit rusty.
any help would be greatly appreciated..
On this line:
if ((lines[i] = malloc(sizeof(char))) == NULL)
you are only allocating memory for a single char, but then try to use the buffer for storing much more than one char of data. Multiply sizeof(char) (which is, by the way, always 1) by the number of chars you are planning to store in the array.
Remember to free() the memory just before the end.
It crashes with a debug error and says stack around variable 'code' was corrupted. This is code for a hamming code lab I am doing. The input file is just a bunch of 1's and 0's on the same line. Why is it crashing?
void processFile(FILE* read, char* InMessage) {
int i = 0, count = 0;
for (i = 0; !feof(read); i++) {
InMessage[i] = fgetc(read);
count++;
}
InMessage[count] = '\0';
}
void hammingCode(char* InMessage) {
int len = strlen(InMessage), i = 0, j = 0;
char code[12], temp[1000];
temp[0] = '\0';
for (i = 0, j = 0; i < len; i++, j++) {
code[j] = InMessage[i];
if (j == 10) {
j = 0;
decode(code);
code[11] = '\0';
strcat_s(temp, sizeof(char)*1000, code);
}
}
strcpy_s(InMessage, sizeof(char)*1000, temp);
}
void decode(char* codeWord) {
int i = 0, j = 0, parity[4] = {0}, diffParity[4] = {0}, twoPower = 0, readNSkip = 0, bitSum = 0;
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
for (j = twoPower; j <= 12; j++) {
if (readNSkip <= twoPower) {
if (j != twoPower) {
parity[i] += codeWord[j-2] - 48;
}
readNSkip++;
}
else {
if (readNSkip == twoPower*2)
readNSkip = 0;
readNSkip++;
}
}
if (parity[i] % 2 == 0)
parity[i] = 0;
else
parity[i] = 1;
if ((codeWord[twoPower-1] - 48) != parity[i])
diffParity[i] = 1;
}
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
bitSum += diffParity[i]*twoPower;
}
codeWord[bitSum] = !codeWord[bitSum];
}
There's two problems I see here:
It looks to me like you are calculating the size of the InMessage buffer incorrectly in your hammingCode function:
int len = strlen(InMessage), i = 0, j = 0;
The strlen function determines the length of the string by finding the position of the first null terminator. If InMessage is not cleared, then this could give you some strange lengths as it will contain a random sequence of bytes. Conversely, if you have cleared the buffer then len will be 0.
To overcome this problem, it is better for the caller to provide the size of the buffer:
int hammingCode (char *InMessage, size_t messageSize)
And use messageSize in place of len.
It's advisable to use this same strategy for your other two functions as well as currently there is a chance of overflowing the provided buffers.
Following on from the previous problem, it may be that the decode function is writing outside the bounds of the buffer. Providing the length of the buffer to decode and adding the appropriate checks to ensure the function does not write outside the given bounds would be a good idea.