So I have the following array fib_sequence in C passed to a function as *fib_sequence[].
My function segfaults when I access an element by doing:
*fib_sequence[i]
However it works when I do:
fib_sequence[0][i]
Am I going insane or are these not equivalent?
For reference here is the entire function, it failed when assigned to index 1 only.
Segfault function
void fib(int *fib_sequence[], int count) {
*fib_sequence = malloc(sizeof(int[count]));
for (int i = 0; i < count; i++) {
if (i == 0) {
*fib_sequence[i] = 0;
} else if (i == 1) {
*fib_sequence[i] = 1;
} else if (i >= 2) {
*fib_sequence[i] = *fib_sequence[i-2] + *fib_sequence[i-1];
}
}
}
Working Function
void fib(int *fib_sequence[], int count) {
*fib_sequence = malloc(sizeof(int[count]));
for (int i = 0; i < count; i++) {
if (i == 0) {
fib_sequence[0][i] = 0;
} else if (i == 1) {
fib_sequence[0][i] = 1;
} else if (i >= 2) {
fib_sequence[0][i] = fib_sequence[0][i-2] + fib_sequence[0][i-1];
}
}
}
*pis not equivalent top[0], though it's always equivalent to*(p + 0)(note the pointer arithmetic here).(*fibSequence)[0].