![](/img/trans.png)
[英]invalid conversion from 'void* (*)(int*)' to 'void* (*)(void*)'
[英]Invalid conversion from void* to int*
我有一個全局變量:
static int *avgg;
在主要功能中:
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();
通過使用mmap,我試圖在父進程和子進程之間共享內存,但是我遇到了錯誤:
invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
您試圖將mmap
的返回值(即void *
隱式轉換為int *
,並且編譯器設置不允許您在沒有顯式強制轉換的情況下執行此操作。
嘗試avgg = (int *)mmap(NULL, sizeof *avgg, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
文檔明確指出mmap
返回void*
,而不返回int*
。
如果您確定數據兼容 , 則可以將前者轉換為后者,但是由於不存在匹配的隱式轉換,因此您需要進行強制轉換。
嗨,您可以使用以下代碼段解決此問題:
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);
}
謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.