这是一个练习试题,我有一些困难:
struct bodytp // Is there an error?
{
char *name; // If so, fix the error.
int len;
};
main()
{
struct bodytp person;
keepname(&person , "Waterman");
printf("%s\n", person.name);
}
void keepname(struct bodytp *onept, const char *last)
{
int len;
char *tpt;
for ( len = 0; last[len] != '\0'; )
len++;
char name[len+1];
for ( tpt = name; *tpt++ = *last++; )
;
onept->name = name;
onept->len = len;
}我已经确定有一个错误,因为当我运行它时,我从printf获得垃圾输出。我还认定,person的name确实是“沃特曼”,是在记事本函数调用之后。我尝试过将person.name取消为person -> name,通过消除符号和运算符以及malloc结构,将问题从基于堆栈的问题更改为基于堆的问题,但没有任何效果。有人能引导我朝着正确的方向前进吗?谢谢。
发布于 2014-10-13 15:20:40
有错误吗?
struct bodytp // Is there an error?
{
char *name; // If so, fix the error.
int len;
};不没有错误。它是一个有效的结构定义。
现在出现错误。:)
主要功能须声明为
int main( void )尽管这不是一个错误,但最好在函数调用之前有一个函数原型。
keepname(&person , "Waterman");程序具有未定义的行为,因为通过本地数组的地址分配指向结构的指针,该指针在退出函数后将被销毁。
void keepname(struct bodytp *onept, const char *last)
{
//...
char name[len+1];
//...
onept->name = name;
//...
}有效的函数可以定义如下
void keepname(struct bodytp *onept, const char *last)
{
int len = 0;
char *tpt;
while ( last[len] != '\0' ) len++;
char *name = malloc( len + 1 );
for ( tpt = name; *tpt++ = *last++; ) ;
onept->name = name;
onept->len = len;
}在这种情况下,您必须释放主内存。
考虑到您可以在函数中使用标准C函数strlen和strcpy。
发布于 2014-10-13 15:17:19
您需要为堆中的名称分配内存。
void keepname(struct bodytp *onept, const char *last)
{
int len;
char *tpt;
for ( len = 0; last[len] != '\0';len++);
char *name=malloc(len+1);
onept->name = name;
onept->len = len;
for ( ; *name++ = *last++ ; );
}https://stackoverflow.com/questions/26343018
复制相似问题