简体   繁体   中英

Invalid conversion from void* to int*

I have a global variable:

static int *avgg;

In main function:

avgg = mmap(NULL, sizeof *avgg, PROT_READ | PROT_WRITE, 
                MAP_SHARED | MAP_ANONYMOUS, -1, 0);

pid_t  pid, wpid;
int status;

 pid = fork();
 if (pid == 0) {
      avg(argc,argv);
      print_avg();

  }
 else{ 
     while ((wpid = wait(&status)) > 0) {

     }
 cout<<"Parent process";
     print_avg();

By using mmap Im trying to share memory between parent and child process but Im getting error:

invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
                 MAP_SHARED | MAP_ANONYMOUS, -1, 0);

You're trying to implicitly convert the return value of mmap , which is a void * , into an int * , and your compiler settings don't allow you to do that without an explicit cast.

Try avgg = (int *)mmap(NULL, sizeof *avgg, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);

The documentation clearly states that mmap returns void* , not int* .

You may convert the former to the latter if you are sure that your data are compatible , but you'll need a cast to do so because no matching implicit conversion exists.

Hi you can fix this problem with this code segment :

 int file_descriptor = shm_open("/test_shared_memory", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
 void *address = mmap ( NULL, size, PROT_READ | PROT_WRITE , MAP_SHARED, file_descriptor, 0);
 // For checking that the address mapped correctly or not.
 if (address == MAP_FAILED) {
    printf("Memory map failed. :(");
    return (EXIT_FAILURE);
 }

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM