[英]I'm hitting a segmentation error when I scanf(%s,lastName); (body code inside)
EDIT: About to try intilizing my chars properly... [didnt work=( ] 编辑:即将尝试正确利用我的字符... [didnt work =(]
EDIT: SOLVED (I can't answer my own question for another 7 hours...) 编辑:已解决(我无法再回答自己的问题7个小时...)
Thanks for the comment Brian, that's just a constant declared at the top.. (it = 20). 感谢您的评论Brian,那只是在顶部声明的常量。(它= 20)。
It turns out the error was happening because I forgot to add a next line after I took in the input name. 事实证明发生了错误,因为我在输入名称后忘记添加下一行。
it's working now =D 现在正在工作= D
:ENDEDIT (lol) :ENDEDIT(大声笑)
I've code my code below, Basically I put in the first name this is supposed to find 我在下面编写了我的代码,基本上,我输入了应该找到的名字
John 约翰
Then I put in the last name... 然后我输入姓氏...
Locke 洛克
and as soon as I enter in "Locke" it hits this error, I feel like maybe it's the scanf and I should be using a better alternative ??? 当我在“ Locke”中输入它时,就会遇到此错误,我觉得这可能是scanf,我应该使用更好的替代方法?
int findPatron(struct Library *lib,struct Patron **p)
{
int i;
char firstName[NAME_LENGTH], lastName[NAME_LENGTH];
printf("\nPlease enter the patron's first name: ");
scanf("%s",firstName);
printf("\nPlease enter the patron's last name: "); //this line prints...
scanf("%s",lastName); //SEGMENTATION ERROR happens here I'm pretty sure.
printf("deerrrr"); //this line never prints
for(i = 0; i<lib->totalPatrons;i++)
{
printf("checking %s %s to %s %s",lib->patrons[i].name.first,lib->patrons[i].name.last,firstName,lastName);
if((strcmp(lib->patrons[i].name.first, firstName) == 0) && (strcmp(lib->patrons[i].name.last, lastName) == 0))
{
**p = lib->patrons[i];
return 0;
break;
}
}
return 1; //No Match!
}
You're getting the segmentation fault after your scanf()
statements. 您在
scanf()
语句之后遇到了分段错误。
If you remove everything after printf("deerrrr");
如果删除
printf("deerrrr");
之后的所有内容printf("deerrrr");
and add a \\n
to that output so the buffer is flushed, you'll find that it all works just fine (provided NAME_LENGTH
is at least 6
given your example input). 并在输出中添加
\\n
,以便刷新缓冲区,您会发现它一切正常(假设您输入的示例名称为NAME_LENGTH
至少为6
)。
Part of programming is knowing how to isolate and debug your problems. 编程的一部分是知道如何隔离和调试问题。
Your issues are with your loop and lib
struct - you're dereferencing something you shouldn't be. 您的问题出在您的循环和
lib
结构上-您在取消引用本不应该的东西。
SEGMENTATION ERROR happens here I'm pretty sure this line never prints
SEGMENTATION ERROR发生在这里,我很确定此行永远不会打印
C's printf is buffered, and only gets flushed by an explicit call to fflush or a blocking action (like scanf, which AFAIK flushes stdout as well), so the error could happen in another place. C的printf被缓冲,并且仅通过显式调用fflush或阻止动作(例如scanf,也由AFAIK刷新stdout)来刷新,因此错误可能在其他地方发生。 Learn to use debugger, that's the proper way of debugging C programs.
学习使用调试器,这是调试C程序的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.