我是用C语言编程的完全新手,我一直在尝试编写一个系统,该系统将接受整数输入,执行计算,并将它们插入字符串中,然后将其传递到共享内存中。如果我是个白痴,但是我得到了一个关于不兼容指针类型的错误,我会道歉。我不知道如何纠正这个错误。编辑:我为最初的问题道歉。包括完整的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
/* The size (in bytes) of shared-memory object */
const int SIZE = 4096;
/* The name of shared-memory object */
const char *Obj = "Shm";
/* The shared-memory file descriptor */
int shm_fd;
/* The pointer to shared-memory object */
void *ptr;
/* Create the shared-memory object */
shm_fd = shm_open(Obj, O_CREAT | O_RDWR, 0666);
/* Configure the size of the shared-memory object */
ftruncate(shm_fd, SIZE);
/* Map the shared-memory object in the address space of the process */
ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED)
{
printf("Map failed\n");
return -1;
}
int cal;
char newStr[200];
char currentStr[200];
char *temp;
char value;
printf("Enter an integer");
scanf("%d", &cal);
/* Create a message and write it to the shared-memory object */
/*fgets(ptr, SIZE, stdin);*/
if (cal == 0) {
printf("0 is not valid");
return -1;
}
if (cal < 1) {
printf("Please enter a positive int");
return -1;
}
sprintf(newStr, "%d", cal);
while (cal != 1) {
if (cal % 2 == 0) {
cal = cal / 2;
}
else {
cal = 3 * cal + 1;
}
value = cal + '0';
sprintf(currentStr, " --- %d", value);
strcat(newStr, currentStr);
}
fgets(ptr, SIZE, newStr);
printf("Writing the message to the shared memory is done! \n");
return 0;
}由于我的编码环境的性质,测试和确定错误的确切性质是特别困难的。
编辑:这是准确的错误消息
Collatz-Producer.c:84:2: warning: passing argument 3 of ‘fgets’ from incompatible pointer type [enabled by default]我已经用ptr删除了上面这一节,因为我确信它能起作用,不过下面是ptr等于什么的具体内容
void *ptr;
ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);发布于 2022-03-25 23:41:33
根据这份文件,函数fgets接受3个参数,顺序如下:
FILE *流,例如stdin数组newStr不是FILE *流。因此,它作为第三个参数是无效的。
如果不打算从FILE *流(如stdin或用fopen打开的文件)读取,则不应该使用fgets函数。
https://stackoverflow.com/questions/71623960
复制相似问题