我正在编写一个使用数组字符串作为邮政编码和家庭地址的注册系统。我使用一个常量来确定邮政编码限制为 8 个字符。 当程序启动寄存器功能时,它使地址和邮政编码输入正确,但是当我列出它时,地址出现正常并且位置1的邮政编码与下面的其他一起出现。为什么会这样?我为邮政编码放置了 8 个字符位置,并且通过放置第二个字符位置来增加。
我的程序:
#include <stdio.h>
#define LIMIT_POSTAL 8
#define LIMIT_REGISTER 5
#define LIMIT_ADDRESS 20
char postal_c[LIMIT_REGISTER][LIMIT_POSTAL], address[LIMIT_REGISTER][LIMIT_ADDRESS];
int line;
void reg()
{
int op;
do
{
printf("Address: ");
scanf("%s", &address[line]);
printf("Postal code: ");
scanf("%s", &postal_c[line]);
op = -1;
printf("1 - Continue\nAny number - Exit\n");
scanf("%d", &op);
line++;
} while(op == 1);
}
int main()
{
int i;
reg();
for(i = 0; i < line; i++)
{
printf("Address: %s\n", address[i]);
printf("Postal: %s\n", postal_c[i]);
}
return 0;
}
输出:
Address: foo
Postal code: 11111111
1 - Continue
Any number - Exit
1
Address: foo2
Postal code: 22222222
1 - Continue
Any number - Exit
0
Address: foo
Postal: 1111111122222222
Address: foo2
Postal: 22222222
答案 0 :(得分:1)
可能在您的代码中:
#include <stdio.h>
#define LIMIT_POSTAL 8
#define LIMIT_REGISTER 5
#define LIMIT_ADDRESS 20
char postal_c[LIMIT_REGISTER][LIMIT_POSTAL], address[LIMIT_REGISTER][LIMIT_ADDRESS];
int line;
void reg()
{
int op;
do
{
printf("Address: ");
scanf("%s", &address[line]);
printf("Postal code: ");
scanf("%s", &postal_c[line]);
op = -1;
printf("1 - Continue\nAny number - Exit\n");
scanf("%d", &op);
line++;
} while(op == 1);
}
int main()
{
int i;
reg();
for(i = 0; i < line; i++)
{
printf("Address: %s\n", address[i]);
printf("Postal: %s\n", postal_c[i]);
}
return 0;
}
我看不到您在程序中初始化了 line
变量,并且您直接使用它来指向索引,因此您没有分配任何值,因此它可能包含垃圾值并指向无效的内存地址在你的程序中。
我假设您的其余代码是正确的。
尝试做...
int line =0;