我正在学校项目上工作,一切正常,但在编译时,我得到了“指针和整数之间的比较”警告。谁能解释为什么会发生这种情况?我在下面的所有四个共享内存初始化中都得到相同的警告。我尝试了不同的方法进行比较。据我所知,shmget和shmat在错误时应该返回-1。即使警告出现了,代码也能很好地工作。我做了更改以提示错误。这些警告在shmat线上提示。下面列出的最小代码。共享内存 - 警告:指针和整数之间的比较
//--------------------------------------------------
//Variables
//--------------------------------------------------
//Shared memory variables
int (*clockVar)[2];
int *turn;
int (*shmMsg)[2];
enum state {idle, want_in, in_cs, done, dne} *flag;
long *pidList;
//Shared memory keys
key_t clockKey;
key_t turnKey;
key_t msgKey;
key_t flagKey;
key_t pidKey;
//Shared memory IDs
int clockID = 0;
int turnID = 0;
int msgID = 0;
int flagID = 0;
int pidID = 0;
//--------------------------------------------------
//Key Initialization
//--------------------------------------------------
clockKey = ftok("ftok_clock", 13);
if (clockKey == -1){
perror("Clock: Failed to load ftok file");
return 1;
}
msgKey = ftok("ftok_msg", 17);
if (msgKey == -1){
perror("Message: Failed to load ftok file");
return 1;
}
flagKey = ftok("ftok_flag", 15);
if (flagKey == -1){
perror("Flag: Failed to load ftok file");
return 1;
}
pidKey = ftok("ftok_pids", 17);
if (pidKey == -1){
perror("PID: Failed to load ftok file");
return 1;
}
//--------------------------------------------------
//Shared Memory Initialization
//--------------------------------------------------
//Initializing shared memory for clock counter
clockID = shmget(clockKey, sizeof(int[2][1]), IPC_CREAT | 0666);
if (clockID == -1){
perror("Clock: Failed to designate shared memory");
return 1;
}
clockVar = shmat(clockID, 0, 0);
if (clockVar == (int*)-1){
perror("Clock: Failed to attach shared memory");
return 1;
}
//Initializing shared memory for the Message array
msgID = shmget(msgKey, sizeof(int[2][1]), IPC_CREAT | 0666);
if (msgID == -1){
perror("Message: Failed to designate shared memory");
return 1;
}
shmMsg = shmat(msgID, NULL, 0);
if (shmMsg == (int*)-1){
perror("Message: Failed to attach shared memory");
return 1;
}
//Initializing shared memory for flag counter
flagID = shmget(flagKey, sizeof(enum state[maxProc]), IPC_CREAT | 0666);
if (flagID == -1){
perror("Flag: Failed to designate shared memory");
return 1;
}
flag = shmat(flagID, NULL, 0);
if (flag == (enum state*)-1){
perror("Flag: Failed to attach shared memory");
return 1;
}
//Initializing shared memory for the process count array
pidID = shmget(pidKey, sizeof(int), IPC_CREAT | 0666);
if (pidID == -1){
perror("PID: Failed to designate shared memory");
return 1;
}
pidList = shmat(pidID, NULL, 0);
if (pidList == (int*)-1){
return 1;
}
编辑:作出建议编辑。标志比较不会再抛出错误(枚举状态*)。现在我得到警告:不同指针类型的比较缺乏对其他三个(clockVar,shmMsg和pidList)的强制转换。我还将我的声明添加到顶部。我相信我只是搞乱了一些语法。谢谢!
'shmget'返回一个'int' ..你的'* ID'变量是什么类型? – yano
我添加了上面的变量,并实现了(可能错误地)Felix建议的更改。添加了注释。 – Arcie