Pass 2D array by reference - c

I want to be able to pass a 2D array to a function, and have it directly change the array in main, so pass by reference. When I try to compile, I get error: expected expression before { in the switch cases. (boardSize=10, but that is not known at compilation time)
void fillBoard(int **, int);
int main() {
int **board = malloc(sizeof(int *) * boardSize);
fillBoard(board, boardSize);
}
void fillBoard(int **board) {
int i, *row = malloc(sizeof(int) * boardSize);
for (i=0; i<boardSize; i++) {
board[i] = malloc(sizeof(int) * boardSize);
switch(i) {
case 1: row = {1,0,1,0,1,1,0,0,1,0}; break;
default: row = {0,0,0,0,0,0,0,0,0,0}; break;
}
board[i] = row;
}
}

There a many different ways to do this. The key is to keep track of what you are addressing where. You can use a single or double pointer to pass and fill board, it all depends on how you want to keep track of the elements. (while the 2-dimensional array, provides a convenience in referencing elements, all values are sequential in memory, and can be accessed with a 1-dimensional reference and offset).
There is one important suggestion when allocating memory for numeric arrays. You must always initialize all elements of the array to protect against attempting to access or dereference an uninitialized value (Undefined behavior). The simple way to do this is to allocate with calloc instead of malloc. calloc allocates and initializes all values to zero (NULL).
Also be aware of the need to track the memory you allocate over the life of your program and free the memory when you no longer need it. This will prevent memory leaks from developing. In a short bit of code like the following, the memory is freed when the program exits. If this were part of some larger code, you would need to free board and board2 when there data was no longer needed.
An example using your original array would be:
#include <stdio.h>
#include <stdlib.h>
#define boardSize 10
void fillBoard_p (int *a);
void fillBoard_p2p (int **a);
int main() {
int i = 0;
int j = 0;
/* declaring board as an integer pointer */
int *board = calloc (boardSize * boardSize, sizeof (*board));
/* declaring board as a pointer to pointer */
int **board2 = calloc (boardSize, sizeof (*board2));
for (i = 0; i < boardSize; i++) {
board2[i] = calloc (boardSize, sizeof (**board2));
}
fillBoard_p (board);
fillBoard_p2p (board2);
printf ("\nboard as an integer pointer:\n");
for (i = 0; i < boardSize * boardSize; i++) {
if (i % boardSize == 0)
printf ("\n %d", board[i]);
else
printf (" %d", board[i]);
}
printf ("\n");
printf ("\nboard2 as an pointer to integer pointer:\n\n");
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
printf (" %d", board2[i][j]);
}
printf ("\n");
}
printf ("\n");
return 0;
}
void fillBoard_p(int *a) {
// 0=WHITE, 1=BLACK
int i = 0;
int j = 0;
int b [][boardSize] = {
{1,0,1,0,1,1,0,0,1,0},
{1,0,1,1,0,0,1,1,1,0},
{0,0,1,0,1,0,1,0,1,1},
{1,1,0,1,1,0,1,0,0,0},
{0,0,1,0,0,0,1,1,0,1},
{1,1,0,1,1,0,0,1,1,0},
{0,0,1,0,0,1,1,0,1,1},
{0,0,1,0,0,1,0,0,0,0},
{1,1,1,1,0,0,1,1,1,1},
{0,1,0,0,1,1,0,0,0,1}
};
for (i = 0; i < boardSize; i++)
for (j = 0; j < boardSize; j++)
a[i*boardSize+j] = b[i][j];
}
void fillBoard_p2p (int **a) {
// 0=WHITE, 1=BLACK
int i = 0;
int j = 0;
int b [][boardSize] = {
{1,0,1,0,1,1,0,0,1,0},
{1,0,1,1,0,0,1,1,1,0},
{0,0,1,0,1,0,1,0,1,1},
{1,1,0,1,1,0,1,0,0,0},
{0,0,1,0,0,0,1,1,0,1},
{1,1,0,1,1,0,0,1,1,0},
{0,0,1,0,0,1,1,0,1,1},
{0,0,1,0,0,1,0,0,0,0},
{1,1,1,1,0,0,1,1,1,1},
{0,1,0,0,1,1,0,0,0,1}
};
for (i = 0; i < boardSize; i++)
for (j = 0; j < boardSize; j++)
a[i][j] = b[i][j];
}
output:
$ ./bin/fillboard
board as an integer pointer:
1 0 1 0 1 1 0 0 1 0
1 0 1 1 0 0 1 1 1 0
0 0 1 0 1 0 1 0 1 1
1 1 0 1 1 0 1 0 0 0
0 0 1 0 0 0 1 1 0 1
1 1 0 1 1 0 0 1 1 0
0 0 1 0 0 1 1 0 1 1
0 0 1 0 0 1 0 0 0 0
1 1 1 1 0 0 1 1 1 1
0 1 0 0 1 1 0 0 0 1
board2 as an pointer to integer pointer:
1 0 1 0 1 1 0 0 1 0
1 0 1 1 0 0 1 1 1 0
0 0 1 0 1 0 1 0 1 1
1 1 0 1 1 0 1 0 0 0
0 0 1 0 0 0 1 1 0 1
1 1 0 1 1 0 0 1 1 0
0 0 1 0 0 1 1 0 1 1
0 0 1 0 0 1 0 0 0 0
1 1 1 1 0 0 1 1 1 1
0 1 0 0 1 1 0 0 0 1
Additionally, since a 2-D array is stored sequentially in memory, you can take advantage of that fact and make use of memcpy (in string.h) to fill the array passed to your function. This can reduce your function to:
void fillBoard_mc (int *a) {
// 0=WHITE, 1=BLACK
int b [][boardSize] = {
{1,0,1,0,1,1,0,0,1,0},
{1,0,1,1,0,0,1,1,1,0},
{0,0,1,0,1,0,1,0,1,1},
{1,1,0,1,1,0,1,0,0,0},
{0,0,1,0,0,0,1,1,0,1},
{1,1,0,1,1,0,0,1,1,0},
{0,0,1,0,0,1,1,0,1,1},
{0,0,1,0,0,1,0,0,0,0},
{1,1,1,1,0,0,1,1,1,1},
{0,1,0,0,1,1,0,0,0,1}
};
memcpy (a, b, boardSize * boardSize * sizeof (int));
}
Were it not for the particularity of the compiler and pointer decay, you could simply use a statically declared array, such as:
int board[boardSize][boardSize] = {{0}};
passing the address of the array to your function (becoming a 3-star programmer):
fillBoard (&board);
with a function similar to:
void fillBoard (int *a[][boardSize]) {
// 0=WHITE, 1=BLACK
int b [][boardSize] = {
{1,0,1,0,1,1,0,0,1,0},
{1,0,1,1,0,0,1,1,1,0},
{0,0,1,0,1,0,1,0,1,1},
{1,1,0,1,1,0,1,0,0,0},
{0,0,1,0,0,0,1,1,0,1},
{1,1,0,1,1,0,0,1,1,0},
{0,0,1,0,0,1,1,0,1,1},
{0,0,1,0,0,1,0,0,0,0},A
{1,1,1,1,0,0,1,1,1,1},
{0,1,0,0,1,1,0,0,0,1}
};
memcpy (a, b, boardSize * boardSize * sizeof (int));
}
Due to pointer decay (board[10][10] => board[*][10]), you will receive an incompatible pointer type warning, despite the function successfully copying the memory as intended. Code that does not compile without warning, should not be relied on in practice.

Related

I cannot understand core dump cause of fgetc, how can I fix it?

I allocated matrix like this :
prevMatrix = (int**)malloc(sizeof(int) * arraySize[0]);
for (int i = 0; i < arraySize[0]; i++) {
prevMatrix[i] = (int*)malloc(sizeof(int) * arraySize[1]);
}
I checked arraySize[] has normal value. arraySize[0] means row, and arraySize[1] means column.
and I handed over the matrix like this :
void getInputMatrix(FILE* input, int column, int** matrix)
getInputMatrix(input, arraySize[1], prevMatrix);
and then function's body is this :
void getInputMatrix(FILE* input, int column, int** matrix) {
int i = 0, j = 0, c = 0;
while (!feof(input)) {
if (j == column) {
j = 0;
i++;
}
c = fgetc(input);
if (c != EOF && c != 32 && c != 10 && c != 13) {
matrix[i][j] = c - 48;
j++;
}
}
}
this is the example of matrix file:
1 0 0 0 0 0 0
0 1 0 1 0 0 0
0 1 0 0 1 1 0
0 1 1 1 0 0 0
0 0 0 0 1 0 0
0 1 0 0 0 1 0
1 0 1 1 0 0 0
0 1 0 0 0 0 1
It works very well in VS 2019, but it cause segmentation fault in Linux system(Ubuntu).
This program works well in Linux till the column is 6 or 7, but it occurs corrupted size vs. prev_size error or segmentation faultwhen the column overs that number.
Is it a problem of allocation? or fgetc()?
How can I fix it?
For starters, your first level allocation should be using the size of an int pointer rather than an int:
int **prevMatrix = malloc(sizeof(int*) * arraySize[0]);
If those types are different sizes, your original code could have a problem.
And, just as an aside, you should not cast the malloc return value in C, it can cause subtle problems.

Implementing 8-Connectivity Hoshen-Kopelman Algorithm in C

I found here an implementation for Hoshen-Kopelman Algorithm, But it checks neighbors only up and left, meaning that a diagonal connection is not considered a connection.
How can I improve this code so that even a diagonal connection will be considered a connection?
In the following example I expect 1 object and not 7 objects:
4 5
1 0 1 0 1
0 1 0 1 0
1 0 1 0 0
0 0 1 0 0
--input--
1 0 1 0 1
0 1 0 1 0
1 0 1 0 0
0 0 1 0 0
--output--
1 0 2 0 3
0 4 0 5 0
6 0 7 0 0
0 0 7 0 0
HK reports 7 clusters found
This is the implementation (full code can be found here):
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* Implementation of Union-Find Algorithm */
/* The 'labels' array has the meaning that labels[x] is an alias for the label x; by
following this chain until x == labels[x], you can find the canonical name of an
equivalence class. The labels start at one; labels[0] is a special value indicating
the highest label already used. */
int* labels;
int n_labels = 0; /* length of the labels array */
/* uf_find returns the canonical label for the equivalence class containing x */
int uf_find(int x)
{
int y = x;
while (labels[y] != y)
y = labels[y];
while (labels[x] != x)
{
int z = labels[x];
labels[x] = y;
x = z;
}
return y;
}
/* uf_union joins two equivalence classes and returns the canonical label of the resulting class. */
int uf_union(int x, int y)
{
return labels[uf_find(x)] = uf_find(y);
}
/* uf_make_set creates a new equivalence class and returns its label */
int uf_make_set(void)
{
labels[0] ++;
assert(labels[0] < n_labels);
labels[labels[0]] = labels[0];
return labels[0];
}
/* uf_intitialize sets up the data structures needed by the union-find implementation. */
void uf_initialize(int max_labels)
{
n_labels = max_labels;
labels = calloc(sizeof(int), n_labels);
labels[0] = 0;
}
/* uf_done frees the memory used by the union-find data structures */
void uf_done(void)
{
n_labels = 0;
free(labels);
labels = 0;
}
/* End Union-Find implementation */
#define max(a,b) (a>b?a:b)
#define min(a,b) (a>b?b:a)
/* print_matrix prints out a matrix that is set up in the "pointer to pointers" scheme
(aka, an array of arrays); this is incompatible with C's usual representation of 2D
arrays, but allows for 2D arrays with dimensions determined at run-time */
void print_matrix(int** matrix, int m, int n)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
printf("%3d ", matrix[i][j]);
printf("\n");
}
}
/* Label the clusters in "matrix". Return the total number of clusters found. */
int hoshen_kopelman(int** matrix, int m, int n)
{
uf_initialize(m * n / 2);
/* scan the matrix */
for (int y = 0; y < m; y++)
{
for (int x = 0; x < n; x++)
{
if (matrix[y][x])
{ // if occupied ...
int up = (y == 0 ? 0 : matrix[y - 1][x]); // look up
int left = (x == 0 ? 0 : matrix[y][x - 1]); // look left
switch (!!up + !!left)
{
case 0:
matrix[y][x] = uf_make_set(); // a new cluster
break;
case 1: // part of an existing cluster
matrix[y][x] = max(up, left); // whichever is nonzero is labelled
break;
case 2: // this site binds two clusters
matrix[y][x] = uf_union(up, left);
break;
}
}
}
}
/* apply the relabeling to the matrix */
/* This is a little bit sneaky.. we create a mapping from the canonical labels
determined by union/find into a new set of canonical labels, which are
guaranteed to be sequential. */
int* new_labels = calloc(sizeof(int), n_labels); // allocate array, initialized to zero
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (matrix[i][j])
{
int x = uf_find(matrix[i][j]);
if (new_labels[x] == 0)
{
new_labels[0]++;
new_labels[x] = new_labels[0];
}
matrix[i][j] = new_labels[x];
}
int total_clusters = new_labels[0];
free(new_labels);
uf_done();
return total_clusters;
}
/* This procedure checks to see that any occupied neighbors of an occupied site
have the same label. */
void check_labelling(int** matrix, int m, int n)
{
int N, S, E, W;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (matrix[i][j])
{
N = (i == 0 ? 0 : matrix[i - 1][j]);
S = (i == m - 1 ? 0 : matrix[i + 1][j]);
E = (j == n - 1 ? 0 : matrix[i][j + 1]);
W = (j == 0 ? 0 : matrix[i][j - 1]);
assert(N == 0 || matrix[i][j] == N);
assert(S == 0 || matrix[i][j] == S);
assert(E == 0 || matrix[i][j] == E);
assert(W == 0 || matrix[i][j] == W);
}
}
/* The sample program reads in a matrix from standard input, runs the HK algorithm on
it, and prints out the results. The form of the input is two integers giving the
dimensions of the matrix, followed by the matrix elements (with data separated by
whitespace).
a sample input file is the following:
8 8
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 1
1 0 0 0 0 1 0 1
1 0 0 1 0 1 0 1
1 0 0 1 0 1 0 1
1 0 0 1 1 1 0 1
1 1 1 1 0 0 0 1
0 0 0 1 1 1 0 1
this sample input gives the following output:
--input--
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 1
1 0 0 0 0 1 0 1
1 0 0 1 0 1 0 1
1 0 0 1 0 1 0 1
1 0 0 1 1 1 0 1
1 1 1 1 0 0 0 1
0 0 0 1 1 1 0 1
--output--
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 1
2 0 0 0 0 2 0 1
2 0 0 2 0 2 0 1
2 0 0 2 0 2 0 1
2 0 0 2 2 2 0 1
2 2 2 2 0 0 0 1
0 0 0 2 2 2 0 1
HK reports 2 clusters found
*/
int main(int argc, char** argv)
{
int m, n;
int** matrix;
/* Read in the matrix from standard input
The whitespace-deliminated matrix input is preceeded
by the number of rows and number of columns */
while (2 == scanf_s("%d %d", &m, &n))
{ // m = rows, n = columns
matrix = (int**)calloc(m, sizeof(int*));
for (int i = 0; i < m; i++)
{
matrix[i] = (int*)calloc(n, sizeof(int));
for (int j = 0; j < n; j++)
scanf_s("%d", &(matrix[i][j]));
}
printf_s(" --input-- \n");
print_matrix(matrix, m, n);
printf(" --output-- \n");
/* Process the matrix */
int clusters = hoshen_kopelman(matrix, m, n);
/* Output the result */
print_matrix(matrix, m, n);
check_labelling(matrix, m, n);
printf("HK reports %d clusters found\n", clusters);
for (int i = 0; i < m; i++)
free(matrix[i]);
free(matrix);
}
return 0;
}
I tried to change the function hoshen_kopelman as described below, but I still get 2 objects instead of 1:
int hoshen_kopelman(int** matrix, int m, int n)
{
uf_initialize(m * n / 2);
/* scan the matrix */
for (int y = 0; y < m; y++)
{
for (int x = 0; x < n; x++)
{
if (matrix[y][x])
{ // if occupied ...
int up = (y == 0 ? 0 : matrix[y - 1][x]); // look up
int left = (x == 0 ? 0 : matrix[y][x - 1]); // look left
// ----------- THE NEW CODE -------------
if (x > 0)
{
if (up == 0 && y > 0) // left+up
up = matrix[y - 1][x - 1];
if (left == 0 && y < m - 1) // left+down
left = matrix[y + 1][x - 1];
}
// ---------- END NEW CODE --------------
switch (!!up + !!left)
{
case 0:
matrix[y][x] = uf_make_set(); // a new cluster
break;
case 1: // part of an existing cluster
matrix[y][x] = max(up, left); // whichever is nonzero is labelled
break;
case 2: // this site binds two clusters
matrix[y][x] = uf_union(up, left);
break;
}
}
}
}
/* apply the relabeling to the matrix */
/* This is a little bit sneaky.. we create a mapping from the canonical labels
determined by union/find into a new set of canonical labels, which are
guaranteed to be sequential. */
int* new_labels = calloc(sizeof(int), n_labels); // allocate array, initialized to zero
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (matrix[i][j])
{
int x = uf_find(matrix[i][j]);
if (new_labels[x] == 0)
{
new_labels[0]++;
new_labels[x] = new_labels[0];
}
matrix[i][j] = new_labels[x];
}
int total_clusters = new_labels[0];
free(new_labels);
uf_done();
return total_clusters;
}
The following output is now obtained (I am expecting 1 and got 2):
4 5
1 0 1 0 1
0 1 0 1 0
1 0 1 0 0
0 0 1 0 0
--input--
1 0 1 0 1
0 1 0 1 0
1 0 1 0 0
0 0 1 0 0
--output--
1 0 1 0 1
0 1 0 1 0
2 0 1 0 0
0 0 1 0 0
HK reports 2 clusters found
What is the correct way to correct the code to check all 8 neighbors?
I led you astray saying to check down-left. The algorithm relies on the current node it is examining being after all the neighbors it checks. So you need to check left, up, up-left, and up-right. You can use this in place of your new code:
if (y > 0)
{
if (left == 0 && x > 0) // left+up
left = matrix[y - 1][x - 1];
if (up == 0 && x < n-1) // right+up
up = matrix[y - 1][x + 1];
}

Boolean Table in 2D array C

I have some dificulties in creating the following array. My task is to fill using recursion a 2D array with all the possible combinations of 0 and 1 taken m times in lexical order. Mathematically speaking there are 2 ^ m combinations.My program just fills the first 3 rows of the array with the same order 0 1 0 1 and then just prints for the rest of the rows 0 0 0 0.
Example
m=4
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
This is my code so far and I appreciate if someone could correct it and explain me what I am doing wrong as I can't spot the mistake myself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void combine(int** arrTF,int m,int n,int row,int col){
if(m==0){
if(row<pow(2,m)){
row++;
combine(arrTF,n,n,row,0);
}else{
return;
}
}else{
arrTF[row][col]=0;
col++;
combine(arrTF,m-1,n,row,col);
arrTF[row][col]=1;
col++;
combine(arrTF,m-1,n,row,col);
}
}
int main(int argc, char *argv[]) {
int m
scanf("%d",&m);
int** arrTF;
arrTF = safeMalloc(pow(2,m)*sizeof(int *));
for (int r=0; r < pow(2,m); r++) {
arrTF[r] = safeMalloc(m*sizeof(int));
}
for(int i=0;i<pow(2,m);i++){
for(int j=0;j<m;j++){
arrTF[i][j]=0;
}
}
combine(arrTF,m,m,0,0);
for(int i=0;i<pow(2,m);i++){
for(int j=0;j<m;j++){
printf("%d ",arrTF[i][j]);
}
printf("\n");
}
return 0;
}
You want all the possible (2^m) combinations of 0's and 1's taken m times in lexical order and you are using a 2D array to store the result.
Things would be very easy if you just want to print all the possible combination of 0's and 1's instead of storing it in 2D array and printing array later.
Storing a combination of 0's and 1's to 2D array is a little bit tricky as every combination is one element of your 2D array.
You want to generate the combination of 0's and 1's in accordance with the recursive algorithm.
So, let's say, at some stage if your algorithm generates the combination 0010 which is stored in an element in 2D array.
And the next combination would be 0011 which the recursive algorithm will generate just by changing the last number from 0 to 1 in the last combination (0010).
So, that means everytime when a combination is generated, you need to copy that combination to its successive location in 2D array.
For e.g. if 0010 is stored at index 2 in 2D array before the algorithm starts computing the next combination, we need to do two things:
Copy the elements of index 2 to index 3
Increase the row number so that last combination will be intact
(Say, this is 2D array)
|0|0|0|0| index 0
|0|0|0|1| index 1
|0|0|1|0| index 2 ---> copy this to its successive location (i.e. at index 3)
|0|0|1|1| index 3 ---> Last combination (index 2) and the last digit is changed from 0 to 1
.....
.....
.....
This we need to do for after every combination generated.
Now, I hope you got where you are making the mistake.
Few practice good to follow:
If you want to allocate memory as well as initialized it with 0, use calloc instead of malloc.
Any math function you are calling again and again for the same input, it's better to call it once and store the result in a variable and use that result where ever required.
Do not include any header file which is not required in your program.
Once done, make sure to free the dynamically allocated memory in your program.
I have made the corrections in your program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void *safeMalloc(size_t n, size_t size) {
void *p = calloc(n, size);
if (p == NULL) {
printf("Error: calloc(%zu) failed. Out of memory!\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void deallocate(int ** ptr, int row) {
for(int i = 0; i<row; i++)
free(ptr[i]);
free(ptr);
}
void combine(int **arrTF, int m, int max_col, int max_row) {
static int row;
if(m==0){
int i;
if (row<(max_row - 1))
{
for(i=0; i<max_col; i++)
arrTF[row+1][i] = arrTF[row][i];
}
row++;
return;
} else {
arrTF[row][max_col-m] = 0;
combine(arrTF, m-1, max_col, max_row);
arrTF[row][max_col-m] = 1;
combine(arrTF, m-1, max_col, max_row);
}
}
int main(int argc, char *argv[]) {
int** arrTF;
int m, max_row;
printf ("Enter number: \n");
scanf("%d", &m);
max_row = pow(2, m);
arrTF = safeMalloc(max_row, sizeof(int *));
for (int r=0; r<max_row; r++) {
arrTF[r] = safeMalloc(m, sizeof(int));
}
combine(arrTF, m, m, max_row);
for(int i=0; i<max_row; i++) {
for(int j=0; j<m; j++) {
printf("%d ", arrTF[i][j]);
}
printf("\n");
}
deallocate(arrTF, max_row);
return 0;
}
Output:
$ ./a.out
Enter number:
2
0 0
0 1
1 0
1 1
$ ./a.out
4
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
Hope this helps.

How to send chunks of a big 2D array to function for processing

I have a 2D array storing image data using int. At this time it is 800x640 but that can change. I want to pass it to another function in 8x8 blocks for processing. I could actually just copy an 8x8 block of the array into a temporary variable and send that to the function and then copy result into another 800x640 array.
However, I want to the function to directly be able to access 8x8 blocks (which will be faster) if I give it the start xy coordinates within this 800x640 array. The problem is that using int** does not work. Also parameter declared as int[8][8] also does not compiled. What do I do? Right now I am writing the program in C++ but eventually shall have to write it in C as well.
You can give the pointer to the original image with other parameters to the function and access each element of your 8x8 area inside the function.
Let's say this is your original 800x640 image:
int img[640][800];
Declare your fuction as:
void work_on_roi(int* img, size_t img_width, size_t img_height, int roi_x, int roi_y, size_t roi_width, size_t roi_height)
ROI stands for region of interest, a widely used term in the field of image processing. In your case, if you want to access roi with (10,20) as its top-left index, you can call this function with arguments as:
work_on_roi(img, 800, 640, 10, 20, 8, 8)
Inside this function, accessing the (i,j) element in the roi would be:
(img + (roi_y + j) * img_width)[roi_x + i]
You can utilize roi_width and roi_height parameter to check for integrity:
// before accessing (i,j) element of roi
assert(i < roi_width);
assert(j < roi_height);
assert(roi_x + i < img_width);
assert(roi_y + j < img_height);
While the way you access the elements of the region will not change depending on how you have declared your array, the way you pass the array as a parameter will change depending on whether you have an actual 2D array or whether you have a pointer-to-pointer-to-type.
In the case of a true array declared similar to int array[X][Y]; (where X and Y are defined constants) you can pass a pointer to array of int [Y], (e.g. (*array)[Y]) as the parameter to your function.
In the case where array is will be converted to a pointer-to-pointer-to-type, when declared similar to int **array; or int (*array)[z]; where you allocate pointers and blocks of each row, or one single block, respectively, you simply pass a pointer-to-pointer-to-type (e.g. int **array)
Taking either case, you could change a region within the array with a simple function that iterates over the elements you wish to change. For example for the case where you have a 2D array as you specify, you could declare a function with logic similar to the following. (You could pass additional parameters as needed to effect whatever change you need)
enum { ROW = 10, COL = 10 }; /* constant definitions */
...
void chgregion (int (*a)[COL], int xs, int ys, int xn, int yn)
{
int xlim = xs + xn, /* xstart + xnumber_of_elements */
ylim = ys + yn; /* same for y */
if (xlim > ROW) xlim = ROW; /* protect array/block bounds */
if (ylim > COL) ylim = COL;
for (int i = xs; i < xlim; i++)
for (int j = ys; j < ylim; j++)
a[i][j] = 1; /* change element as required */
}
Above the a pointer to an array of COL elements is passed along with the x and y starting position within the array and the number of elements in the region, e.g. xn and yn. A simple check is done to limit the region size to remain within the array bounds or bounds of a block of memory. If your array is actually a pointer-to-pointer-to-type, just pass int **a instead and pass the dimensions of the block of memory as additional parameters.
You can put together a simple test as follows:
#include <stdio.h>
enum { ROW = 10, COL = 10 };
void chgregion (int (*a)[COL], int xs, int ys, int xn, int yn);
void prna (int (*a)[COL]);
int main (void) {
int a[ROW][COL] = {{0}};
prna (a);
chgregion (a, 2, 2, 6, 6);
putchar ('\n');
prna (a);
return 0;
}
void chgregion (int (*a)[COL], int xs, int ys, int xn, int yn)
{
int xlim = xs + xn,
ylim = ys + yn;
if (xlim > ROW) xlim = ROW;
if (ylim > COL) ylim = COL;
for (int i = xs; i < xlim; i++)
for (int j = ys; j < ylim; j++)
a[i][j] = 1;
}
void prna (int (*a)[COL])
{
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++)
printf ("%2d", a[i][j]);
putchar ('\n');
}
}
Example Use/Output
$ ./bin/array2d_region
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 1 1 1 1 1 0 0
0 0 1 1 1 1 1 1 0 0
0 0 1 1 1 1 1 1 0 0
0 0 1 1 1 1 1 1 0 0
0 0 1 1 1 1 1 1 0 0
0 0 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Let me know if this is what you were intending, or if what you are doing differs in some way. For further help, please post a Minimal, Complete, and Verifiable example.

Segfault while allotting 2D array using double dimensional pointer

I'm currently working on a codechef practice problem http://www.codechef.com/problems/STEPUP#
I'm trying to set up a 2D array using pointers to accept the data and enter in into the 2D array as i receive it using scanf.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
int m,n,i,k,j;
int ex;
scanf("%d",&ex);
for(i=0;i<ex;i++)
{
int **edgegraph=NULL,temp1,temp2;
scanf("%d %d",&n,&m);
edgegraph=malloc(m*sizeof(int));
for(k=0;k<m;k++)
{
*(edgegraph+k)=malloc(m*sizeof(int));
if(!*(edgegraph+k))
exit(0);
}
for(k=0;k<m;k++)
{
scanf("%d %d",&temp1,&temp2);
*(*(edgegraph+m*temp1)+temp2)=1;
}
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
printf("%d ",*(*(edgegraph+m*i)+j));
printf("\n");
}
}
}
The error i get is
(gdb) run
Starting program: /home/vishwa/codechef/valid
2
2 2
1 2
Program received signal SIGSEGV, Segmentation fault.
0x000000000040079d in main (argc=1, argv=0x7fffffffded8) at validedge.c:24
24 *(*(edgegraph+m*temp1)+temp2)=1;
(gdb) quit
What I intend to do is create an m*m matrix, set all valid edges to 1 and then sort in ascending order of number of edges. I'm unsure if this will solve the problem, but would like to know where I'm messing up.
You malloc the wrong number of bytes: edgegraph=malloc(m*sizeof(int)); should have malloc(m * sizeof(int *)); . To avoid this sort of error you can use the following pattern:
ptr = malloc( N * sizeof *ptr );
which always allocates N of whatever ptr is a pointer to.
Next, the syntax x[y] is much simpler to read than *(x+y) especially when the expressions get complicated. Using that syntax would have avoided the mistake dconman points outs. You seem to have put an extra m * into your calculation where it is not required.
Also you mix up m and n later in your code. To avoid this sort of error, use more descriptive variable names.
So a fixed version of your allocation code could look like:
if ( 2 != scanf("%d %d",&num_edges, &num_vertices) )
exit(EXIT_FAILURE);
edgegraph = malloc( num_vertices * sizeof *edgegraph );
for (int vertex = 0; vertex < num_vertices; ++vertex)
{
edgegraph[vertex] = malloc( num_vertices * sizeof **edgegraph );
if ( edgegraph[vertex] == NULL )
exit(EXIT_FAILURE);
}
Note that it is possible to replace that malloc series with a single allocation:
int (*edgegraph)[num_vertices] = malloc( num_vertices * sizeof *edgegraph );
Moving onto your code to read edges. You wrote for(k=0;k<m;k++) however I think you meant n there. Using more descriptive variable names and the x[y] syntax:
for(int edge = 0; edge < num_edges; ++edge)
{
if ( 2 != scanf("%d %d",&temp1,&temp2) )
exit(EXIT_FAILURE);
if ( temp1 < 0 || temp1 >= num_vertices || temp2 < 0 || temp2 >= num_vertices )
exit(EXIT_FAILURE); // maybe display an error message
edgegraph[temp1][temp2] = 1;
edgegraph[temp2][temp1] = 1; // add this if undirected graph!
}
Now the final loop, for(i=0;i<m;i++). You have used the same variable i as control variable for this loop and for your outer loop. To avoid this sort of error, use scoped control variables:
for (int i = 0; i < num_edges; ++i)
Finally you will need to free the memory you malloc'd at the end of each time around the outer loop.
You are so close: lose the m* in your expressions to access an array element. Remember, you set up your 2d array as an array of rows, each with its own pointer (you allocated each independently).
*(*(edgegraph+m*temp1)+temp2)=1;
should be
*(*(edgegraph+temp1)+temp2)=1;
And the same change where you do that later in your code.
Is there a reason you are not using array indices?
EDIT
here is my input
2
10
10
4 3
4 9
7 3
3 7
4 3
4 5
7 4
3 5
9 0
5 2
And I got this output
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 1 0 0
0 0 0 1 0 1 0 0 0 1
0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0

Resources