如果我定义这样的类:
struct _HNum
{
char *a;
};
typedef struct _HNum HNum;
然后写一个函数:
/*
*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)
{
HNum newNum;
if(!newNum.a)
{
return NULL;
}
strcpy(newNum.a, hnum.a);
}
编译器在“hnum”上给出“表达式必须具有类类型”错误
在strcpy(newNum.a, hnum.a);
行。这有什么问题?
答案 0 :(得分:3)
这是因为hnum
是一个指针。因此,您需要取消引用它 - 明确地使用星号,或使用->
运算符而不是点.
:
strcpy(newNum.a, hnum->a);
注意:您需要添加内存分配和return
语句,否则您的程序会有未定义的行为:
HNum *HNum_clone(const HNum *hnum)
{
if(!hnum)
{
return NULL;
}
HNum *newNum = malloc(sizeof(HNum));
if (hnum->a) {
newNum->a = malloc(strlen(hnum->a)+1);
strcpy(newNum->a, hnum->a);
}
else
{
newNum->a = NULL;
}
return newNum;
}
答案 1 :(得分:0)
这段代码好吗?
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 = (HNum*)malloc(sizeof(HNum));
newNum->a = (char*)malloc(2);
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;
}