我正在尝试使用fgets
从用户那里接受多行,但是当我离开时,我的 Segmentation fault (core dumped)
。我可以在循环中毫无疑问的情况下 printf
address
和 part_of_address
变量,而在循环中,它可以按预期工作。一旦摆脱了循环,它就会着火。
// Define a char array called 'name' accepting up to 25 characters.
char name[25];
// Define a char array called 'part_of_address' accepting up to 80 characters.
char part_of_address[80];
// Define a char array called 'address' accepting up to 80 characters.
char address[80];
// Clean the buffer, just to be safe...
int c;
while ((c = getchar()) != 'n' && c != EOF) {};
// Ask for the user to enter a name for the record using fgets and stdin, store
// the result on the 'name' char array.
printf("nEnter the name of the user (RETURN when done):");
fgets(name, 25, stdin);
// Ask for the user to enter multiple lines for the address of the record, capture
// each line using fgets to 'part_of_address'
printf("nEnter the address of the user (DOUBLE-RETURN when done):");
while (1)
{
fgets(part_of_address, 80, stdin);
// If the user hit RETURN on a new line, stop capturing.
if (strlen(part_of_address) == 1)
{
// User hit RETURN
break;
}
// Concatinate the line 'part_of_address' to the multi line 'address'
strcat(address, part_of_address);
}
printf("This doesn't print...");
正如迈克尔·沃尔茨(Michael Walz)注释时所指出的,即使在没有初始化的address
的情况下,您也会使用strcat(address, part_of_address);
。由于它是一个自动阵列,因此包含不确定的值,您正在调用未定义的行为。即使是第一个strcat
也可能会在address
数组之后覆盖内存。
只需使用char address[80] = "";
或char address[80] = {' '};