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);
}

Just having a quick look at your code, you're not declaring your variables of type SYM correctly - you need to prefix the declarations with "struct". If you don't want to do this, you'll need to use a typedef.

Yeah, i know, but it's just "C++ style", as our professor recommends to use this type of declaration. And for visual studio it has no difference, as it's a c++ compiler.

I know and i'm sorry if it's against your rules. But it's the one and olny non-C declaration in the whole code, so, maybe, it's not an Armageddon?
I can just change the code if you like or repost it to C++, but it's not the real problem, you know... And i'm afraid, that in C++ section i'll be kicked too, as there's no classes :('
Maybe some real help, please? It's not easy to find a mistake in your own code.

Sorry, i see it's not an ANSI code, so this thread should be deleted.

Edited 7 Years Ago by Sobakaa: n/a

SYM *temp=(SYM*)malloc(sizeof(SYM));

I think this is enough.

This question has already been answered. Start a new discussion instead.