Related
I have written code for dynamic programming, matrix chain multiplication algorithm. For this question, I am not concerned with the implementation details of algorithm.
I am trying to debug it using gdb. However, I am having a hard time examining cost_table 2-D array inside matrix_chain_order function.
Inside matrix_chain_order function, I set a breakpoint and examine the cost_table 2-D array. I have also used printf statements there.
The printf statements print the correct value of a cell in cost_table.
I found some revelant information in this SO QA: how to print 2d arry values in gdb.
I did not understand what the answer really explained. But it gave me a direction, so I tried printing cost_table and its cell values in gdb. (Session below)
Code:
/* MATRIX-CHAIN-MULTIPLICATION - CLRS 3rd Edition, Chapter 15 */
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#define array_length(arr) (sizeof(arr) == 0 ? 0 : sizeof(arr) / sizeof((arr)[0]));
/* define input sequence to matrix_chain_order function */
const int INPUT_SEQUENCE[] = {4, 10, 3, 12, 20};
/* DEFINE m[i, j]:
* Let m[i, j] be the minimum number of scalar multiplications needed to compute
* matrix A_suffix_i..j; for the full problem, the lowest cost way to compute A_suffix_1..n
* would thus be m[1, n].
*/
/* The function computes the rows from bottom to top and from left to right within
* each row.
* It computes each entry m[i, j] using products p_suffix_i-1 * p_suffix_k * p_suffix_j
* for k = i, i + 1, ...., j - 1 and all entries southwest and southeast from m[i, j].
*
* This prodedure assumes that matrix A_suffix_i has dimensions p_suffix_i-1 * p_suffix_i
* for i = 1, 2, ...., n.
* Its input is a sequence p = <p_suffix_0, p_suffix_1, ...., p_suffix_n>, where
* p.length = n + 1.
*
* The procedure uses an auxiliary table m[1 ..n, 1 ..n] for storing the m[i, j] costs,
* and another auxiliary table s[1 ..n - 1, 2 ..] that records which index of k achieved
* the optimal cost in computing m[i, j].
*/
void matrix_chain_order (int ct_rows, int ct_cols, int cost_table[ct_rows][ct_cols], int kit_rows, int kit_cols, int k_idx_table[kit_rows][kit_cols]);
int main ()
{
int sequence_len = array_length(INPUT_SEQUENCE);
/* initialize table (2-D array), m[1 ..n, 1..n] */
int m = 0, n = 0;
int cost_table[sequence_len][sequence_len];
for (m = 0; m < sequence_len; m++) {
for (n = 0; n < sequence_len; n++) {
/* m[i, i] = 0, for i = 1, 2, ...., n (the minimum costs for chains of length 1) */
if (n == m) {
cost_table[m][n] = 0;
} else {
cost_table[m][n] = INT_MAX;
}
}
}
/* initialize table (2-D array), s[1 ..n - 1, 2..n] */
int o = 0, p = 0;
int k_idx_table[sequence_len - 1][sequence_len - 1];
for (o = 0; o < sequence_len - 1; o++) {
for (p = 0; p < sequence_len - 1; p++) {
k_idx_table[o][p] = -1;
}
}
matrix_chain_order(sequence_len, sequence_len, cost_table, sequence_len, sequence_len - 1, k_idx_table);
return 0;
}
/* NOTE on array passed to the function. */
/* When you pass an array to a function, it decays into a pointer to the first element,
* at which point knowledge of its size is lost. You need to work it out before decay
* and pass that information with the array.
*/
void matrix_chain_order(int ct_rows, int ct_cols, int cost_table[ct_rows][ct_cols], int kit_rows, int kit_cols, int k_idx_table[kit_rows][kit_cols])
{
int sequence_len = array_length(INPUT_SEQUENCE);
/* use recurrence,
*
* min[i, j] = 0 , if i = j
* min[i, j] = min {m[i, k] + m[k + 1, j] + p_suffix_i-1 * p_suffix_k * p_suffix_j , if i < j
*
* to compute m[i, i + 1] for i = 1, 2, ...., n - 1 (the minimum costs of chains of length l = 2)
* during the first execution of the for loop.
* The second time through the loop, it computes m[i, i + 2] for i = 1, 2, ...., n - 2
* (the minimum costs for chains of length l = 3), and so forth.
*/
int chain_len = 0, i = 1, j = 0, k = 0, cost = INT_MAX;
for (chain_len = 2; chain_len <= sequence_len; chain_len++) {
for (i = 1; i <= sequence_len - chain_len + 1; i++) {
j = i + chain_len - 1;
for (k = i; k <= j - 1; k++) {
/* at each step, the m[i, j] cost computed depends only on table entries m[i, k] and m[k + 1, j]
* already computed
*/
printf("Printed cost_table[%d][%d] : %d\n", i, k, cost_table[i][k]);
printf("Printed cost_table[%d][%d] : %d\n", (k+1), j, cost_table[k+1][j]);
cost = cost_table[i][k] + cost_table[k + 1][j] + INPUT_SEQUENCE[i - 1] * INPUT_SEQUENCE[k] * INPUT_SEQUENCE[j];
if (cost < cost_table[i][j]) {
cost_table[i][j] = cost;
k_idx_table[i][j] = k;
}
}
}
}
}
gdb session:
(gdb) p ((int (*) [5][5]) cost_table)[1][1]
$3 = {0, 0, 65280, 0, -8944}
(gdb) p (int [][5]) *cost_table
$4 = 0x7fffffffdca0
(gdb) p (int [5][5]) *cost_table
Invalid cast.
(gdb) p (int [][5]) **cost_table
warning: array element type size does not divide object size in cast
$5 = 0x7fffffffdca0
(gdb) p (int [][5]) *cost_table
$6 = 0x7fffffffdca0
(gdb) p (int [][5]) cost_table
warning: array element type size does not divide object size in cast
$7 = 0x7fffffffdbe0
(gdb) p cost_table#5#5
$16 = {{0x7fffffffdca0, 0x500000005, 0x26, 0x100000002, 0x500000001}, {0x7fffffff00000002, 0x4, 0x3, 0x1f7ffe728, 0x7fffffffdca0}, {0x0, 0x5, 0x7fffffffddf0, 0x400952 <main+892>, 0xffffffffffffffff}, {
0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}, {0xffffffffffffffff, 0xffffffffffffffff, 0x0, 0x7fffffffde10, 0x7fffffff00000000}}
(gdb) p *cost_table#5#5
$17 = {{{0, 2147483647, 2147483647, 2147483647, 2147483647}, {2147483647, 0, 2147483647, 2147483647, 2147483647}, {2147483647, 2147483647, 0, 2147483647, 2147483647}, {2147483647, 2147483647,
2147483647, 0, 2147483647}, {2147483647, 2147483647, 2147483647, 2147483647, 0}}, {{0, -140389360, 32767, 4, 0}, {0, 0, 65280, 0, -8944}, {32767, 4, 0, 0, 0}, {4, 0, 0, 0, 4}, {0, 0, 0, 4, 0}}, {{
0, 0, 0, 5, 5}, {4, 4, 5, 4, 0}, {4, 0, -9056, 32767, 3}, {0, 3, 0, -9136, 32767}, {1781326592, 1051810453, 0, 0, 0}}, {{0, 4195552, 0, -8496, 32767}, {0, 0, 0, 0, 4197632}, {0, -140322768, 32767,
0, 0}, {-8488, 32767, 0, 1, 4195798}, {0, 0, 0, 1661416990, 1731120}}, {{4195552, 0, -8496, 32767, 0}, {0, 0, 0, -989383138, -1731249}, {-690538978, -1735179, 0, 0, 0}, {0, 0, 0, 1, 0}, {4195798,
0, 4197744, 0, 0}}}
(gdb) p **cost_table#5#5
$18 = {{0, 2147483647, 2147483647, 2147483647, 2147483647}, {2147483647, 0, 2147483647, 2147483647, 2147483647}, {2147483647, 2147483647, 0, 2147483647, 2147483647}, {2147483647, 2147483647, 2147483647,
0, 2147483647}, {2147483647, 2147483647, 2147483647, 2147483647, 0}}
(gdb) p cost_table[i][k]
Cannot perform pointer math on incomplete types, try casting to a known type, or void *.
I don't get how the commands that I have used in gdb session result in their respective outputs.
Why am I unable to use p cost_table[i][k] directly in gdb,
whereas the printf statements print the result in execution of
code?
p ((int (*) [5][5]) cost_table)[1][1]: What happens if I change
value of numbers in this command or if I do something like
p ((int(*) [][5]) cost_table)[1][1]?
Why is the output of p *cost_table#5#5 and p **cost_table#5#5 so
different?
My requirement is to be able to examine the cost_table and its cells in gdb.
Any other suggestions is welcomed.
Just ask gbd for it :)
Breakpoint 2, matrix_chain_order (ct_rows=5, ct_cols=5, cost_table=0x7fffffffdac0, kit_rows=5, kit_cols=4, k_idx_table=0x7fffffffda80) at delme.c:96
96 printf("Printed cost_table[%d][%d] : %d\n", (k+1), j, cost_table[k+1][j]);
(gdb) ptype cost_table
type = int (*)[5]
(gdb) p ((int (*) [5])cost_table)[i][j]
$12 = 2147483647
You may also go up one frame ('up' in gdb) and print directly cost_table[idx1][idx2] but it is probably less user friendly to debug in the loop...
the type gdb gives (int(*)[5]) stand for pointer to array 5 of int (see
https://cdecl.org/?q=int+%28*t%29%5B5%5D if you want to experience the syntax.)
The array type decays that's why only a pointer remains; you may have a look to Manipulate multidimensional array in a function for more explanation in C.
I need help to modify the solution I came up with for a programming challenge. The problem statement says as follows:
Martin the zebra of Madagascar (the movie) wants to fill the hole that's left to cover in the floor of the hut that is building in the edge of the beach. The hole has length L and Martin has many pieces of wood, some with length s and others with length t. As Martin is very distracted he wants to know in how many ways the hole can be filled by putting pieces of wood at will.
Input specification
The only line of input contains three integers L, s and t separated with a space (1 <= L, s, t <= 10^6, s != t).
Output specification
A line with the number of different ways to fill the hole modulo 10^9 + 7 (1000000007).
Sample input
6 2 3
Sample output
2
The solution I submitted, uses this function to count:
#include <iostream>
#include <vector>
using namespace std;
int ** create(int n, int m) {
int ** a = new int*[
for (int i = 0; i < n; i++) {
a[i] = new int[m];
a[i][0] = 1; // I assumed there is one way to fill a hole of length zero
}
return a;
}
int count(vector<int> stick, int n, int m) { // Counts ways to fill the hole
int ** fill = create(n + 1, m + 1);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (j < stick[i - 1])
fill[i][j] = fill[i - 1][j] % 1000000007;
else
fill[i][j] = (fill[i - 1][j] + fill[i][j - stick[i - 1]]) % 1000000007;
return fill[n][m];
}
int main() {
int l, a, b;
cin >> l >> a >> b;
vector<int> stick{a, b};
cout << count(stick, stick.size(), l) << endl;
return 0;
}
The problem is that this only counts the different sets that can fill the hole completely, for example:
Say we have a hole of length L = 6 and sticks of lengths s = 1 and t = 2, my function returns 4. This are the four sets that my function is counting:
{1, 1, 1, 1, 1, 1}
{1, 1, 1, 1, 2}
{1, 1, 2, 2}
{2, 2, 2}
But what it's required are all the permutations of this sets, hence this should return 13, that is:
{1, 1, 1, 1, 1, 1}
{1, 1, 1, 1, 2}
{1, 1, 1, 2, 1}
{1, 1, 2, 1, 1}
{1, 2, 1, 1, 1}
{2, 1, 1, 1, 1}
{1, 1, 2, 2}
{1, 2, 1, 2}
{2, 1, 1, 2}
{1, 2, 2, 1}
{2, 1, 2, 1}
{2, 2, 1, 1}
{2, 2, 2}
How can I modify my function to count all the permutations? Is there any material that can help me understand how to build a dynamic programming solutions for this kind of problems?
let d[i] - number of ways to fill the hole of length i
then d[i] = d[i-s] + d[i-t]
d[0] = 1
d[i < 0] = 0 obviously
I am writing a C program to generate Keys and test them in an encryption function. However since I have NEVER written a C program before, and I'm completely unused to having manage memory manually, I have run into a problem. I have a memory leak and to be honest, I don't know how to solve it. I understand I need to release the memory at some point but can't until I've run through all keys and I run out of memory before I get through all of them. Writing the program in a different language is NOT an option so please do not suggest that. The code that is leaking is shown below, any help would be appreciated.
EDIT: I know i haven't called a free function to free the memory. I don't see where I can put it because I need the memory until i run through all keys. Putting it outside the loops doesn't solve the problem because the leak occurs inside the loops
2nd EDIT: Posted the full program. I do not have the option of using data structures (i.e. the bool arrays) other than those shown because of how the DES encrypt function(which I did not write) works
#include <stdio.h>
#include <stdlib.h>
#include "des.h"
void dec2bin(bool *testaRR, bool *to_return, int convert);
int main(int argc, const char * argv[])
{
// insert code here...
bool testKey[56] = {
0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 1
};
bool testKey2[56] = {//intuitive key reversed for testing
1, 0, 0, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0
};
bool output[64];
bool input[64] = {//the reverse of below... DES bits are numbered left to right, in order of least to most significant so we must enter the bit values in reverse.
//forexample the binary vale of N is 01001110 but below is displayed as 01110010
1, 0, 0, 0, 1, 1, 0, 0,//1
0, 0, 0, 0, 1, 1, 0, 0,//0
1, 1, 0, 0, 0, 0, 1, 0,//C
1, 0, 1, 0, 0, 0, 1, 0,//E
1, 1, 0, 0, 1, 0, 1, 0,//S
0, 0, 1, 0, 1, 0, 1, 0,//T
1, 0, 1, 0, 0, 0, 1, 0,//E
0, 1, 1, 1, 0, 0, 1, 0 //N
};
int y = sizeof(input);
printf("(Input MSG: ");
for (int i = y-4; i >= 0; i-=4)
printf("%X", input[i]+2*input[i+1]+4*input[i+2]+8*input[i+3]);//this is the conversion to hex code
printf(")\n");
/*
use char[] to store the key as set of
*/
/*bool input[64] = {//this is the given plaintext message in the intuitive order (opposite of what it is)
0, 1, 0, 0, 1, 1, 1, 0,//N
0, 1, 0, 0, 0, 1, 0, 1,//E
0, 1, 0, 1, 0, 1, 0, 0,//T
0, 1, 0, 1, 0, 0, 1, 1,//S
0, 1, 0, 0, 0, 1, 0, 1,//E
0, 1, 0, 0, 0, 0, 1, 1,//C
0, 0, 1, 1, 0, 0, 0, 0,//0
0, 0, 1, 1, 0, 0, 0, 1 //1
};
int y = sizeof(input);
printf("(Input MSG: ");
for (int j = 0; j < y; j+=4)
printf("%X", input[j+3]+2*input[j+2]+4*input[j+1]+8*input[j]);//this is the conversion to hex code
printf(")\n");*/
bool test [8];
bool returned[8];
char keyphrase [8];
keyphrase[7] = 0;
for(int start = 65; start<=90; start++)
{
//dec2bin(test, returned, start);
keyphrase[0] = start;
for(int two = 65; two<=90; two++){
keyphrase[1]=two;
for(int three = 65; three<=90; three++){
keyphrase[2]=three;
for(int four = 65; four<=90; four++){
keyphrase[3]=four;
for(int five = 65;five<=90;five++){
keyphrase[4]=five;
for( int six = 65; six <=90; six++){
keyphrase[5]=six;
for(int seven = 65; seven <=90; seven++){
keyphrase[6]=seven;
printf("%s \n", keyphrase);
}
}}
}
}
}
//once i fix the memory leak I will be calling the EncryptDes Function here and checking the outputblk agains the given cipher text
}
free(keyphrase);
int k = sizeof(testKey);
printf("(Test Key: ");
for (int z = 0; z < k; z+=7)
printf("%d", testKey[z+7]+2*testKey[z+6]+4*testKey[z+5]+8*testKey[z+4]+16*testKey[z+3]+32*testKey[z+2]+64*testKey[z+1]+ 128*testKey[z]);//this is the conversion to hex code
printf(")\n");
//loop on the key (starting at
EncryptDES(testKey, output, input, 0);
int x = sizeof(output);
printf("(Output MSG: ");
for (int i = 0; i < x; i+=4)
printf("%X", output[i+3]+2*output[i+2]+4*output[i+1]+8*output[i]);//this is the conversion to hex code
printf(")\n");
return 0;
}
void dec2bin (bool *testaRR, bool *to_return, int convert)
{
printf("%d : ", convert);
printf("%c", convert);
printf("\n ");
//bool testaRR [8];
for(int st = 0; st<8; st++){
testaRR[st] = convert%2;
to_return[7-st] = testaRR[st];
//printf("%d :", 7-st);
//printf(" %d spot ", st);
convert = convert/2;
//testaRR stores the arrays in one direction
//to_return stores them in the other
//Example:
//65 = 01000001 testaRR least significant on the far right (m0st sig is in index 7)better for storage and keeping track of where the bits actually are in binary
//65 = 10000010 to_return least significant on the far left (same as DES) (most significant bit is index 0) good for printing to screen
}
You do not need dynamic memory management here.
Start with
char keyphrase[8];
keyphrase[7]=0;
instead of your malloc and you will be good to go. Your highest array index is 7 (the terminating NUL), and hence you need an array of 8 items (0..7).
If you really want to use malloc, simply a free() at the end will be fine, but you need to malloc 8 characters and set keyphrase[7] to 0 to do the terminating NUL still.
Here's a tested version that works:
#include <stdio.h>
/* compile with gcc -Wall -std=c99 keyphrase.c -o keyphrase */
int
main (int argc, char **argv)
{
char keyphrase[8];
keyphrase[7] = 0;
for (int start = 65; start <= 90; start++)
{
//dec2bin(test, returned, start);
keyphrase[0] = start;
for (int two = 65; two <= 90; two++)
{
keyphrase[1] = two;
for (int three = 65; three <= 90; three++)
{
keyphrase[2] = three;
for (int four = 65; four <= 90; four++)
{
keyphrase[3] = four;
for (int five = 65; five <= 90; five++)
{
keyphrase[4] = five;
for (int six = 65; six <= 90; six++)
{
keyphrase[5] = six;
for (int seven = 65; seven <= 90; seven++)
{
keyphrase[6] = seven;
printf ("%s \n", keyphrase);
}
}
}
}
}
}
}
}
The real problem is the use of printf. You did not NULL terminate keyphrase, so every time you printf you overflow.
Also, to avoid the memory leak, simply replace char *keyphrase = (char *)malloc(7); with char keyphrase[8];.
You're calling malloc on the first line but I don't see a single free to release what you allocated. After all the loops are completed (i.e. usage of the allocated data is complete) you must call free(keyphrase);
New answer as the program has been modified.
You say your program is using all memory 'because I'm watching the available memory go down from over 4 free GB to about 5 MB'.
I'm guessing the answer is not the loops but these lines:
//loop on the key (starting at
EncryptDES(testKey, output, input, 0);
int x = sizeof(output);
We can't see the source to or declaration of EncryptDES, but you aren't passing a length to it. If 0 is meant to be the length, this would explain it.
The next line however suggests that output is meant to be an array of 64 bytes (rather than 2 strings). But EncryptDES would have no way of knowing this.
I suggest you run the whole thing under valgrind to find out what is happening.
I have an array of 10 elements, and I need to make that array into its moving average equivalent.
Using 3 elements each time (eg average of elements at indices 0-2, then 1-3 and so on up to indices from 10 then back to 0 and 1 to make the new array have exactly 10 elements as well).
What is the best approach to this without using pointers to wrap the array around (ring buffer).
Just do some bounds checking and wrap the index in code.
The example code below can be made more efficient, but it's written like this for clarity (sort of). Also there may be some minor mistake since I'm typing into StackOverflow rather than compiling it.
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int averages[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < 10; i++)
{
int a = i;
int b = i + 1 > 9 ? i - 10 + 1;
int c = i + 2 > 9 ? i - 10 + 2;
int count = array[a] + array[b] + array[c];
int average = count / 3; // note this will truncate any decimal part
averages[i] = average;
}
I've been thinking if there is any smarter solution if I want to check all eight neighbors of an arbitrary element in a binary number only 2D array in C
What I do is:
Psudo Code:
//return how many neighbor of an element at x,y equals 1.
int neighbor(int** array, int x, int y)
if x>WIDTH
error
if y>HIEGHT
error
if x==0
ignore west, nw, sw, and calculate the rest.....
etc..
this is pretty dull, is there any smarter solution?
I used a similar approach to get Adjacent Mines for a particular cell in the Minesweeper Game. What I did, is I used an Array like this (MAX_NUMBER_OF_CELLS = 8) :
int offset[MAX_NUMBER_OF_CELLS][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
Considering we are talking about the CELL at location 0, 0 in a matrix. We will simply add these offset values, to the CELL to check, if the adjacent CELL is a valid CELL (i.e. it falls within the matrix). If it is VALID, then we will see if it contains 1, if yes than increment sum by 1 else not.
//rest of the values represent x and y that we are calculating
(-1, -1) (-1, 0) (-1, 1)
-------------------------
(0, -1) |(0, 0(This is i and j))| (0, 1)
-------------------------
(1, -1) (1, 0) (1, 1)
sum = 0;
for (k = 0; k < MAX_NUMBER_OF_CELLS; k++)
{
indexX = i + offset[k][0];
indexY = j + offset[k][1];
if (isValidCell(indexX, indexY, model)) // Here check if new CELL is VALID
// whether indexX >= 0 && indexX < rows
// and indexY >= 0 && indexY < columns
{
flag = 1;
if (arr[indexX][indexY] == 1))
sum += 1;
}
}
EDIT 1 :
Here is one working example (C is not my language, though still tried my hands on it to give you one idea :-)) :
#include <stdio.h>
#include <stdlib.h>
int findAdjacent(int [4][4], int, int, int, int);
int main(void)
{
int arr[4][4] = {
{0, 1, 0, 0},
{1, 0, 1, 1},
{0, 1, 0, 0},
{0, 0, 0, 0}
};
int i = 2, j = 2;
int sum = findAdjacent(arr, i, j, 4, 4);
printf("Adjacent cells from (%d, %d) with value 1 : %d\n", i, j, sum);
return EXIT_SUCCESS;
}
int findAdjacent(int arr[4][4], int i, int j, int rows, int columns)
{
int sum = 0, k = 0;
int x = -1, y = -1; // Location of the new CELL, which
// we will find after adding offsets
// to the present value of i and j
int offset[8][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
for (k = 0; k < 8; k++)
{
x = i + offset[k][0];
y = j + offset[k][1];
if (isValidCell(x, y, rows, columns))
{
if (arr[x][y] == 1)
sum += 1;
}
}
return sum;
}
int isValidCell(int x, int y, int rows, int columns)
{
if ((x >= 0 && x < rows) && (y >= 0 && y < columns))
return 1;
return 0;
}
One possible optimization, if you want to know the number of neighbors of cells a lot more than you want to change the cells, is to preprocess the number of neighbors for each cell and save the results in an another array.
int** actualArray;
// fill in with 0s and 1s
int** numberOfNeighbors;
// write a function to calculate the number of neighbors for cell x,y in actualArray and
// store the result in numberOfNeighbors[x][y]
preprocess(actualArray, numberOfNeighbors); // call this whenever actualArray changes
// now you can get the number of neighbors of a cell in constant time
// from numberOfNeighbors[x][y]
Are you trying to find the current position of the element in the array? If so, you can define a macro like:
#define OFFSET(x,y) ((GridWidth*y)+x)
Or, if you're trying to find which surrounding 'boxes' could contain an element (i.e which neighbors are 'in bounds')...
for k = 0 while k < GridWidth
for m = 0 while m < GridWidth
if k < GridWidth
toRight = true
if m < GridWidth
toDown = true
if k > 1
toLeft = true
if m > 1
toUp = true
From there, combine the directions to get diagonals - if toRight && toUp, then toUpRight=true etc
EDIT - I forgot to mention, this is if the grid is stored in a 1d array. For 2d, m would be for GridHeight