[英]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: 通过使用mmap,我试图在父进程和子进程之间共享内存,但是我遇到了错误:
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. 您试图将
mmap
的返回值(即void *
隐式转换为int *
,并且编译器设置不允许您在没有显式强制转换的情况下执行此操作。
Try avgg = (int *)mmap(NULL, sizeof *avgg, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
尝试
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*
. 文档明确指出
mmap
返回void*
,而不返回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. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.