Pointers in Cilk Cilk supports pointers, allowing you to pass references to values and records within your program.
```cilk
#include <stdio.h>
#include <cilk/cilk.h>
// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr` . `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
void zeroval(int ival) {
ival = 0;
}
// `zeroptr` in contrast has an `int*` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then *dereferences* the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
void zeroptr(int* iptr) {
*iptr = 0;
}
int main() {
int i = 1;
printf("initial: %d\n", i);
zeroval(i);
printf("zeroval: %d\n", i);
// The `&i` syntax gives the memory address of `i` ,
// i.e. a pointer to `i` .
zeroptr(&i);
printf("zeroptr: %d\n", i);
// Pointers can be printed too.
printf("pointer: %p\n", (void*)&i);
return 0;
}
zeroval
doesn’t change the i
in main
, but zeroptr
does because it has a reference to the memory address for that variable.
To compile and run this Cilk program:
$ clang -fcilkplus pointers.c -o pointers
$ ./pointers
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x7ffd5e7e57dc
In Cilk, pointers work similarly to C. The main difference is that Cilk extends C with parallelism constructs, but those aren’t used in this particular example. The pointer syntax and semantics remain the same as in standard C.