请告诉我我的代码有什么问题:
#include "stdio.h"
struct rights_on_cmd{
char *gtm_cmd; /*set ,zrite ,kill...*/
char value; /*y or n*/
} ;
struct usr_rights{
char *username;/*user name*/
struct rights_on_cmd rights[]; /*list gtm command & right on this command for user*/
};
struct rights_on_gbl{
char *gbl_name;
struct usr_rights user_list[]; /*list users have and specific right on global*/
};
int main(){
int i ;
struct rights_on_gbl gbl_list[2];
for(i = 0;i <= 2; i = i + 1){
struct rights_on_gbl gbl;
char gbl_name[20];
printf("Input global variable name: ");
scanf("%s",&gbl_name);
int j;
gbl.gbl_name = gbl_name;
printf("******Setting for global : %s\n",gbl_name);
for(j = 0;j <= 2 ; j = j + 1) {
char username[20];
struct usr_rights user;
char *set,kill,zwrite;
struct rights_on_cmd set_cmd ,kill_cmd,zwrite_cmd;
printf("Input username: ");
scanf("%s",&username);
printf("Does user %s have permission on set: [y/n] ",username);
scanf("%s",&set);
set_cmd.gtm_cmd = "set";
set_cmd.value = set;
user.rights[0] = set_cmd;
printf("Does user %s have permission on kill: [y/n] ",username);
scanf("%s",&kill);
kill_cmd.gtm_cmd = "kill";
kill_cmd.value = kill;
user.rights[1] = kill_cmd;
printf("Does user %s have permission on zwrite: [y/n] ",username);
scanf("%s",&zwrite);
zwrite_cmd.gtm_cmd = "zwrite";
zwrite_cmd.value = zwrite;
user.rights[2] = zwrite_cmd;
user.username = username;
gbl.user_list[j] = user;
};
gbl_list[i] = gbl;
};
int f ;
for(f = 0; f < 2 ; f++){
printf("%s",gbl_list[f].gbl_name);
}
return 0;
}
它在以下位置获得不定式循环:
for(j = 0;j <= 2 ; j = j + 1) {
....
}
我无法找到每个循环后j
索引不会增加的原因
谢谢,
//更新:此评论仅用于绕过添加代码而不是评论
答案 0 :(得分:1)
问题:
所有这些
scanf("%s",&gbl_name);
scanf("%s",&username);
scanf("%s",&set);
scanf("%s",&kill);
scanf("%s",&zwrite);
应该是
scanf("%s", gbl_name);
scanf("%s", username);
scanf(" %c", &set);
scanf(" %c", &kill);
scanf(" %c", &zwrite); /* The reason for using %c is explaned below */
因为%s
中的scanf
需要char*
,而不是char(*)[20]
或char**
。
你有
char *set,kill,zwrite;
宣布char*
set
和两个char
s kill
和zwrite
。它应该像
char set, kill, zwrite;
因为你想输入字符而不是字符串。这就是问题#1中最后三个scanf
使用%c
的原因。
答案 1 :(得分:0)
您正在访问未初始化的数组rights []和user_list []; 使用malloc为它们分配内存,或定义边界。 为考试:
struct usr_rights{
char *username;/*user name*/
struct rights_on_cmd rights[3]; /* << HERE */
};
struct rights_on_gbl{
char *gbl_name;
struct usr_rights user_list[3]; /* << and HERE*/
};
答案 2 :(得分:0)
你的部分代码中有缓冲区溢出,你编程的行为是不可预测的。
检查这些
的界限user.rights[0] = set_cmd;
user.rights[1] = kill_cmd;
user.rights[2] = zwrite_cmd;
gbl.user_list[j] = user;