C ++: array and shared memory

I am trying to create a piece of shared memory to split an array, here is my example:

int main(){
    key_t key;
    int shm_id;
    int arr[10];

    key=ftok("~/.bashrc",1);

    shm_id = shmget(key, 10*sizeof(int), 0666 | IPC_CREAT);

    arr = (int*)shmat(shm_id, NULL, 0);

    arr[0]=101;
    printf("%d\n",arr[0]);


}

When compiling, I get the following error:

error: incompatible types in assignment of ‘int*’ to ‘int [10]’

What is wrong with my assignment?

+3
source share
3 answers

Remove this line:

int arr[10];

and change the call to shmat () to:

int* arr = (int*)shmat(shm_id, NULL, 0);

A pointer variable can be used as an array, so it arr[0]=101will work.

(As @Andrew noted, it is better to declare variables at the point where they are used for the first time. This reduces the risk of using an uninitialized variable.)

+2
source

You should declare arras a pointer, not an array:

int* arr;

You cannot assign a pointer to an array and shmat()returns a pointer.

+7

When you write arr [10], you allocate an array of elements on the stack. Implicitly, this means that the value & arr [0] (which is really a pointer to the first element in arr) cannot be changed. If you want to copy the contents of shmat into an arr array, you need to use memcpy()either some similar method to set the contents of arr correctly.

+1
source

All Articles