首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从不兼容的指针类型传递‘fget’的参数3[默认启用]

从不兼容的指针类型传递‘fget’的参数3[默认启用]
EN

Stack Overflow用户
提问于 2022-03-25 23:00:26
回答 1查看 179关注 0票数 1

我是用C语言编程的完全新手,我一直在尝试编写一个系统,该系统将接受整数输入,执行计算,并将它们插入字符串中,然后将其传递到共享内存中。如果我是个白痴,但是我得到了一个关于不兼容指针类型的错误,我会道歉。我不知道如何纠正这个错误。编辑:我为最初的问题道歉。包括完整的代码

代码语言:javascript
复制
#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;
}

由于我的编码环境的性质,测试和确定错误的确切性质是特别困难的。

编辑:这是准确的错误消息

代码语言:javascript
复制
Collatz-Producer.c:84:2: warning: passing argument 3 of ‘fgets’ from incompatible pointer type [enabled by default]

我已经用ptr删除了上面这一节,因为我确信它能起作用,不过下面是ptr等于什么的具体内容

代码语言:javascript
复制
void *ptr;
ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-25 23:41:33

根据这份文件,函数fgets接受3个参数,顺序如下:

  1. 指向要写入的内存缓冲区的指针。
  2. 内存缓冲区的大小。
  3. 要读取的FILE *流,例如stdin

数组newStr不是FILE *流。因此,它作为第三个参数是无效的。

如果不打算从FILE *流(如stdin或用fopen打开的文件)读取,则不应该使用fgets函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71623960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档