Initialize C array at definition depending on runtime input Best way to initialize rr and cc depending on cycle number to pre-defined values in r and c.

int func(int cycle, int index, int i) {
  char *rr;
  char *cc;

  if (cycle % 2 == 0) {
      char r[4] = { 0, -1, 0, 1 };
      char c[4] = { 1, 0, -1, 0 };
      rr = r;
      cc = c;
  }
  else {
      char r[4] = { -1, -1, 1, 1 };
      char c[4] = { 1, -1, -1, 1 };
      rr = r;
      cc = c;
  }

  return(index + rr[i] + cc[i]);
}
This code is not correct. The r[4] and c[4] arrays you have are stored on the stack, which means that as soon as they go out of scope the data is no longer valid and you get undefined behavior because rr and cc now point to unused (and possibly overwritten) areas on the stack.

If you wanted to do this correctly, you could ensure that the arrays are kept alive either by storing on the heap, static memory, or high enough on the stack that they will live as long as rr and cc are used.

After reading it again, I realized I made a mistake. While the temporary r and c arrays are initialized in their own scopes that are immediately exited, the arrays themselves live on the same stack with the rest of the function. Still, it's definitely a bad habit to have use variables after they've left the scope even if they're technically still on the stack, so I would make the same changes anyway.

For example, you could do:

// Somewhere in a high enough scope (possibly the current one) or static
char r_1[4] = { 0, -1, 0, 1 };
char c_1[4] = { 1, 0, -1, 0 };

char r_2[4] = { -1, -1, 1, 1 };
char c_2[4] = { 1, -1, -1, 1 };

// In the current scope
char *rr;
char *cc;

if (cycle % 2 == 0) {
  rr = r_1;
  cc = c_1;
}
else {
  rr = r_2;
  cc = c_2;
}