2012-03-20 47 views
2

shmgetを2次元配列で使用しようとしています。 これは私のコードです:C:2次元配列のshmget

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 **に代入することはできず、2次元配列のように使うことはできません。実際、char *は論理的に2次元配列として簡単に扱うことができます。