根据DDD我从strcpy得到了一个seg错误但是我无法弄清楚我做错了什么(对C来说仍然很新)。非常感谢任何帮助,提前谢谢。
int compare_people(PERSON* first, PERSON* second)
{
char firstName[32];
char secondName[32];
strcpy(firstName, first->name);
strcpy(secondName, second->name);
int returnVal = strcmp(firstName, secondName);
return returnVal;
}
答案 0 :(得分:2)
似乎第一个或第二个等于NULL或first-> name或second-> name等于NULL或具有由于使用strcpy超过32个字符的非零终止数据。 另一个原因可能是first-> name或second-> name具有无效指针,例如指向已经销毁的本地数据的指针。
在功能中插入支票。例如
assert( first != NULL && second != NULL &&
first->name != NULL && second->name != NULL &&
strlen( first->name ) < 32 && strlen( second->name ) < 32 );
或者你可以在几个单独的断言中拆分这个断言。
答案 1 :(得分:0)
just try that code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char name[25];
}PERSON;
int compare_people(PERSON* first, PERSON* second);
main()
{
PERSON *first,*second;
first=(PERSON *)malloc(sizeof(PERSON));
printf("Enter the first name\n");
scanf("%s",first->name);
second=(PERSON *)malloc(sizeof(PERSON));
printf("Enter the second name\n");
scanf("%s",second->name);
if((compare_people(first,second)) == 0)
printf("Two names are same \n");
else
printf("Two names are different\n");
}
int compare_people(PERSON* first, PERSON* second)
{
char firstName[32];
char secondName[32];
strcpy(firstName, first->name);
strcpy(secondName, second->name);
int returnVal = strcmp(firstName, secondName);
return returnVal
}
〜