Hi, guys, i need some help, as i can't find a mistake in my code for some hours.
I'm expiriencing a problem in function makeCodes, which should make huffman codes for my symbols. In my head this works just fine, recursively making codes, but my Visual Studio crashes on the first strcpy. What's wrong? Maybe i have no permission to copy strings, or anything?
P.S. Sorry for my english

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define SIZE 256

struct SYM
{
	unsigned char ch; //ascii
	float freq; //symbol frequency
	char code[SIZE]; //new huffman code
	SYM *left; //left hand of tree
	SYM *right; //right hand of tree
};

SYM* huffTree(SYM *syms[], int N) //array of SYM structs and size N
{
	SYM *temp=(SYM*)malloc(sizeof(SYM));

	temp->freq=syms[N-1]->freq+syms[N-2]->freq;
	temp->code[0]=0;
	temp->left=0;
	temp->right=0;

	temp->left=syms[N-2];
	temp->right=syms[N-1];

	if(N==2)
		return temp;
	else
	{
		for(int i=0;i<N;i++)
		{
			if(temp->freq>syms[i]->freq)
			{
				syms[N-1]=syms[i];
				syms[i]=temp;
				temp=syms[N-1];
			}
		}
		return huffTree(syms, N-1);
	}
}

void makeCodes(SYM *root)
{
	if (root->left)
	{
		strcpy(root->left->code,root->code);
		strcat(root->left->code,"0");
		makeCodes(root->left);
	}
	if (root->right)
	{
		strcpy(root->right->code,root->code);
		strcat(root->right->code,"1");
		makeCodes(root->right);
	}
}

int main()
{
	int i=5;

	SYM *syms[SIZE];
	SYM arr[SIZE];

	arr[0].ch='a';
	arr[0].freq=0.4;
	arr[1].ch='b';
	arr[1].freq=0.3;
	arr[2].ch='c';
	arr[2].freq=0.1;
	arr[3].ch='d';
	arr[3].freq=0.1;
	arr[4].ch='e';
	arr[4].freq=0.1;
	syms[0]=&arr[0];
	syms[1]=&arr[1];
	syms[2]=&arr[2];
	syms[3]=&arr[3];
	syms[4]=&arr[4];

	SYM* root=huffTree(syms, i);
	makeCodes(root);
}

Please, i need some help, as it stops my work on a compressor.

i noticed on line 17 you a creating a new SYM object. have you tried using the new keyword?

SYM * temp = new SYM[N];  // using the size you passed into the function for the array

I can't belive this, but it was some visual studio bug - i used some kind of a trasformation tool from 2005 to 2008 version, and it works! without even a trouble! Thank you for your advices, now i really understand my code :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.