I'm getting several errors when trying to run the *HNum_clone
function. Probably missing something really stupid? HNum is supposed to represent a number of any length.
typedef struct _HNum
{
char *a;
}HNum;
/*
* Allocates a new HNum and sets its value to 0.
* RETURN VALUE:
* Returns a pointer to the new number, or NULL if the allocation failed.
*/
HNum *HNum_alloc()
{
HNum *newNum;
newNum->a = (char*)malloc(2*sizeof(char));
if(!newNum->a) return NULL;
newNum->a = "0";
return newNum;
}
/*
*Allocates a new HNum with the same value as hnum. It is the caller's
* responsibility to free the returned HNum.
* RETURN VALUE:
* Returns a pointer to the new number, or NULL if the allocation failed.
*/
HNum *HNum_clone(const HNum *hnum)
{
if(!hnum)
{
return NULL;
}
HNum *newNum = HNum_alloc();
if (hnum->a) {
strcpy(newNum->a, hnum->a);
}
else
{
newNum->a = NULL;
}
return newNum;
}
*Changed to the code below, still getting the same errors:
HNum *HNum_alloc(void)
{
HNum *newNum = (HNum*)malloc(sizeof *newNum);
if(newNum != NULL)
{
newNum->a = (char*)malloc(2);
if(newNum->a != NULL)
{
strcpy(newNum->a, "0");
return newNum;
}
free(newNum);
}
return NULL;
}
HNum *HNum_clone(const HNum *hnum)
{
if(!hnum)
{
return NULL;
}
HNum *newNum = (HNum*)malloc(sizeof *newNum);
if(newNum != NULL)
{
newNum->a = (char*)malloc(strlen(hnum->a)+1);
if(newNum->a != NULL)
{
strcpy(newNum->a, hnum->a);
return newNum;
}
}
return NULL;
}
Changed HNum_clone
to the following, seems to be working now. Looks like the problem was that HNum *newNum
wasn't defined at the start of the function...
HNum *HNum_clone(const HNum *hnum)
{
HNum *newNum = HNum_alloc();
if(!hnum)
{
return NULL;
}
if(newNum != NULL)
{
free(newNum->a);
newNum->a = (char*)malloc(strlen(hnum->a)+1);
if(newNum->a != NULL)
{
strcpy(newNum->a, hnum->a);
return newNum;
}
}
return NULL;
}