C_190418_array
C_190418_array
-
error
: variably modified at file scope
help text 1
help text 2
1、#define LISTEN_NUM 10 /*The MAX Number Of Users*/
2、const int LISTEN_NUM = 10;
/*UserProfile Struct, to store user's infomation*/
typedef struct {
char username[10]; /*User Name*/
char userip[20]; /*User IP*/
int isOnline; /*Is Online*/
} UserProfile;
UserProfile users[LISTEN_NUM];//Users
若用2的方式,则用gcc编译会出现Error: variably modified 'users' at file scope
改成1的形式,则没有报错信息。
-
原因:
因为由const定义的是变量,用define定义的宏是常量。C++中可以这么用,但是C中不能这么用。在c里静态数组(固定长度的数组,即LISTEN_NUM位置是常数)是允许的,而动态数组(譬如给数组的长度是用变量来表示的)不能写成UserProfile users[LISTEN_NUM];形式的,只能自行分配内存。
- example
-
notice|待改进
: 无序,当同时满足胜利条件时无法判断先后顺序
#include <stdio.h>
#include <stdlib.h>
#define size 3// 3*3
//const int size=3; //variably modified 'board' at file scope
int board[size][size]; //init 3*3 array
int i=0,j=0;//i:row j:column
int numofx,cx;
int numofo,co;
int result =-1;//tag:no one win
int main(){
//input the array
printf("please input your board:\n");
for(i=0;i<size;i++){
for(j=0;j<size;j++){
scanf("%d",&board[i][j]);
}
}
printf("your board is :");
for(i=0;i<size;i++){
printf("\n");
for(j=0;j<size;j++){
printf("%d\t",board[i][j]);
}
}
//check the winner on row and column
//00 01 02
//10 11 12
//20 21 22
for(i=0;i<size && result==-1;i++){//result !=-1 no one win
numofx=numofo=cx=co=0;//number of 0,1 is 0
for(j=0;j<size;j++){
if(board[i][j]==0) numofo++;//round1: 00 01 02
else if(board[i][j]==1)numofx++;
if(board[j][i]==0)co++;//round1:00 10 20
else if(board[j][i]==1)cx++;
//test
//printf("\ni=%d j=%d\nfo=%d",i,j,numofo);
//printf(" co=%d",co);
}//for2
if(numofx==size||cx==size) result=1;
else if(numofo==size||co==size) result =0;
}//for1
//check the winner on diagonal
//00 01 02
//10 11 12
//20 21 22
// state 1
numofx=numofo=cx=co=0;//init the value
for(i=0;i<size && result==-1;i++){
//00 11 22
//i=j
//only have three possible value,it's not necessary to check the result (-1)
if(board[i][i]==1)cx++;
else if (board[i][i]==0)co++;
}
if(cx==size) result=1;
else if(co==size) result =0;
//state 2
numofx=numofo=cx=co=0;//init the value
for(i=0;i<size && result==-1;i++){
//02 11 20
//i+j=size-1
// i and j have the math connect ,use i to express j,just one "for" cycle
if(board[i][size-1-i]==0)co++;
else if (board[i][size-1-i]==1)cx++;
}
if(cx==size) result=1;
else if(co==size) result =0;
if(result!=-1)
printf("\nthe winner is player %d",result);
else printf("\nno winner!");
}//main
please input your board:
1 0 1
0 1 0
1 0 0
your board is :
1 0 1
0 1 0
1 0 0
the winner is player 1
please input your board:
0 1 0
0 1 0
1 0 1
your board is :
0 1 0
0 1 0
1 0 1
no winner!
- specially
please input your board:
1 1 0
1 1 0
1 1 0
your board is :
1 1 0
1 1 0
1 1 0
the winner is player 1
同时满足胜利条件但result为1
因为先执行 行列判断
判断顺序如下:
R&C
1.0R 2
.0C(First meet condition,result =1
)
3.1R 4.1C
5.2R 6.2C
diagonal
7.00 11 22
8.02 11 20