2012-03-20 139 views
2

我尝试使用shmget与二维数组。 这是我的代码:C:shmget与2D阵列

char **array; 
key_t key; 
int size; 
int shm_id; 
int i = 0; 
void *addr; 

key = // here I get the key with ftok() 
size = (21 * sizeof(char *)) + (21 * sizeof(char **)); 
shm_id = // here I get the shmid with shmget() 

if (shm_id == -1) // Creation 
{ 
    array = (char **)shmat(shm_id, NULL, SHM_R | SHM_W); 
    while (i != 20) 
    { 
     array[i] = memset(array[i], ' ', 20); 
     array[i][20] = '\0'; 
     i++; 
    } 
    array[i] = NULL; 
    shm_id = // here I get the shmid with the flag IPC_CREAT to create the shared memory 
    addr = shmat(shm_id, NULL, SHM_R | SHM_W); 
} 

但是我有个段故障与行 “排列[I] = memset的(阵列[I], '',20);”

我在做什么错?

回答

2

您应该首先检查shmget是否成功。如果共享内存的分配失败,那么你不能使用共享内存! ;-) Like:

If (shm_id = shmget(.......) == -1) { 
exit(1); 
} 
else { 
/* proceed with your work*/ 
} 

和shmat也是一样。

shmget返回void *。你不能将它分配给一个char **,并像使用二维数组一样使用它。事实上,char *可以很容易地在逻辑上作为2D数组处理。