barfatchen
barfatchen

Reputation: 1698

A pointer/array issue in C

I have followed the following webpage:

http://www.1024cores.net/home/lock-free-algorithms/reader-writer-problem/improved-lock-free-seqlock

the source is like following:

struct data_t 
{ 
    int seq; // sequence number 
    int data [1024]; // user data 
}; 

struct seqlock_t 
{ 
    data_t* current; 
    data_t pool [16]; // 16 user objects are held 
}; 

seqlock_t sl; 

The structure is quite simple, what confuses me is the following:

data_t* d0 = sl.current; // load-consume
int idx = (sl.current - sl.pool + 1) % 16; 
data_t* d = &sl.pool[idx]; 

The sl.current is a pointer, sl.pool is? What current - pool can achieve? in c language view, how should I explain this statement?

int idx = (sl.current - sl.pool + 1) % 16;

Edit :

Thanks for all information , it help a lot !!! in my own coding style would use int idx = (sl.current - &[sl.pool[0]) + 1) % 16; now I know &(sl.pool[0]) is the same with sl.pool !!! I should figure it out , the following example , what I read before , showes pointer/array ....

void display(int *p)
{
    int idx ;
    printf("(%d)(%d)\n",*p,p[1]) ;
}
int main()
{
    int i,Arr[10] ;
    for(i=0;i<10;i++)
        Arr[i] = i + 100;
    display(Arr) ;
}

Yes , I can use display(Arr) and display(&Arr[0]) , they are the same ~!!

Upvotes: 1

Views: 174

Answers (3)

glglgl
glglgl

Reputation: 91017

data_t* d0 = sl.current; // load-consume

gets the pointer into a local variable or even a register in order to access easier.

int idx = (sl.current - sl.pool + 1) % 16; 

It is assumed that sl.current points to one of the elements of the array sl.pool. So sl.current - sl.pool gets the respective distances in terms of data_t *, so it gets the current index. + 1 advances to the next index and with % 16 you achieve that a value of 16 - which would be illegal - points to 0 instead.

data_t* d = &sl.pool[idx];

This points to the new one; I suppose later comes a sl.current = d or something like that.

Upvotes: 2

rcs
rcs

Reputation: 7187

sl.current is a pointer. sl.pool is an array, and by writing like that it is equal to &sl.pool[0]. So it points to the first element of the array. We can do some pointer operations such as subtraction, in that case to obtain some index.

I find this link http://www.eskimo.com/~scs/cclass/notes/sx10b.html quite simple to understand some pointer arithmetic.

Upvotes: 6

Abhineet
Abhineet

Reputation: 5389

From what I can deduce by the given information::

int idx = (sl.current - sl.pool + 1) % 16; 
data_t* d = &sl.pool[idx]; 

s1.pool is an array. So, negating s1.pool will give some value, say int x. Now ((x+1) % 16) will give a valid array bound index for s1.pool which is stored in idx. And thus, they found a valid array index for second line processing.

Upvotes: 1

Related Questions