我正在尝试在C中填充二维数组。一切运行良好,但不会打印分配给数组的值。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
main()
{
char parkingspace[25][4];
char CarReg[7], validreg[7];
int row, position;
printf( "Enter the car Registration number \n" );
fgets( CarReg, sizeof( CarReg ), stdin );
if( isdigit( CarReg[0] )&& isdigit( CarReg[1] ) && (CarReg[2]=='H' ) && ( CarReg[3]=='I' ) && ( CarReg[4]=='R' ) && ( CarReg[5]=='E' ))
{
puts( "Valid Registration \n" );
printf( "==================================================\n\n\n" );
}
else
{
puts( "Invalid registration .\n Please put a value of two digits followed by the word HIRE! in caps" );
}
printf( "You entered: %s\n", CarReg );
if( isdigit( CarReg[0] )&& isdigit( CarReg[1] ) && ( CarReg[2]=='H' ) && (CarReg[3]=='I' ) && ( CarReg[4]=='R' ) && ( CarReg[5]=='E' ))
{
strcpy(validreg, CarReg);
printf( "Accepted Car Reg is : %s\n\n\n\n", validreg );
printf( "==================================================\n\n\n");
}
for (row=1; row<26; row++)
{
for (position=1;position<5; position++)
{
parkingspace[row][position]=validreg;
printf("parkingspace \t row[%d] position[%d] =[ %c ]\n", row,position,parkingspace[row][position]);
}
}
}
答案 0 :(得分:1)
您遇到的一个问题是数组的索引从零到数组大小减去一。因此,row
的有效索引为0
到24
,而不是1
到25
。
另一个问题是您尝试将字符数组分配给单个字符:
parkingspace[row][position]=validreg;
如果您只需要validreg
中parkingspace[row]
的前四个字符,那么请执行以下操作:像这样的内循环:
for (position=0; position < 4; position++)
{
parkingspace[row][position] = validreg[position];
printf("parkingspace \t row[%d] position[%d] =[ %c ]\n", row, position, parkingspace[row][position]);
}
答案 1 :(得分:0)
你在第39行犯了错误
parkingspace[row][position]=validreg;
应该是
parkingspace[row][position]=validreg[position];
答案 2 :(得分:0)
for (row=1; row<26; row++)
{
for (position=1;position<5; position++)
这两行应该修改为
for (row = 0; row < 24; row ++)
{
for (position =0; position < 3; poisition++)
这是因为你已宣布为char parkingspace [25] [4]; 数组从索引'0'开始,直到(size - 1)