C int array issue - c

my output values
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define W 160
#define H 105
struct dungeons {
int x;
int y;
int width;
int height;
};
void randomNumberGenerator(int seed);
void makeGameBoard(int gameBoard[W][H]);
void makeDungeonRooms(struct dungeons d[10]);
void printGame(int gameBoard[W][H]);
int main(int argc, char *argv[]) {
int gameBoard[W][H];
//int gameBoard[160][105] = {2};
struct dungeons d[10];
makeGameBoard(gameBoard);
makeDungeonRooms(d);
printGame(gameBoard);
return 0;
}
void randomNumberGenerator(int seed) {
srand(seed);
}
void makeGameBoard(int gameBoard[160][105]) {
int i;
int j;
for (j = 0; j < 105; j++) {
for (i = 0; i < 160; i++) {
gameBoard[i][j] = 2;
//gameBoard[i][j] = 2;
/*
if (j == 0) {
gameBoard[i][j] = 2;
} else
if (j == 104) {
gameBoard[i][j] = 2;
} else
if (i == 0) {
gameBoard[i][j] = 2;
} else
if (i == 159) {
gameBoard[i][j] = 2;
} else {
gameBoard[i][j] = 4;
}
*/
}
}
gameBoard[0][1] = 2;
gameBoard[0][0] = 2;
gameBoard[159][0] = 3;
}
void makeDungeonRooms(struct dungeons d[10]) {
int i;
for (i = 0; i < W; i++) {
d[i].x = 0;
d[i].y = 0;
d[i].width = 0;
d[i].height = 0;
}
}
void printGame(int g[W][H]) {
int i;
int j;
for (i = 0; i < W; i++) {
for (j = 0; j < H; j++) {
printf("%d", g[i][j]);
/*
if (g[i][j] == 2) {
printf("|");
} else
if (g[i][j] == 1) {
printf("X");
} else {
printf(" ");
}
*/
}
printf("\n");
}
}
I'm making a grid. But the first 5 rows and half of the 6th row, when printed output the value 0. I'm setting everything to 2 in the for loop, and even after when I try to manually change the value, it still doesn't. The last one [159][0] works but nothing in the first 5 rows and half of the 6th seem to work. They stay 0. Why?

The problem is here:
void makeDungeonRooms(struct dungeons d [10]){
int i;
for(i = 0; i< W; i++){
d[i].x = 0;
d[i].y = 0;
d[i].width = 0;
d[i].height = 0;
}
}
where #define W 160. Accessing array out of bound can trigger undefined behavior. It can trigger a segmentation fault, it can remain unnoticed for a long time or alter the output of the program in very strange ways. Here, zeroing the dungeons also partly zeroed the gameBoard. Keep it that way: your game is going to be hilarious!

Related

The pointer variables overflows when they store integers larger than 1024 and some adresses seem to be locked.in C

How do I get to write to 2D pointers where I have pnumber[2%4][2%4] and how can I get pnumber with more than 3 ciphers to be displayed?
I'm making a program to write pascals triangle in C.
When the pointer pnumbers[i][j] have both i and j = 2 mod 4, except for when i and j = 2, then my program won't write to the address and give the error message:
pascals triangle: malloc.c:2406: sysmalloc: Assertion '{old_top == initial_top (av) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int factorial(int p) {
if (p>=1) {
return p*factorial(p-1);
}
else {
return 1;
}
}
int NchooseM(int n, int m) {
return factorial(n)/(factorial(n-m)*factorial(m));
}
int main() {
int n =7;
int x = n-2;
int i, j, k;
/*
printf("How many rows of Pascals triangle do you want to write?\n");
scanf("%d", &n);
*/
int **pnumbers;
pnumbers = (int **) malloc(n *sizeof(int *));
/* Allocate memory for storing the individual elements in a row */
for (i = 0; i < n; i++) {
pnumbers[i] = (int *) malloc(i * sizeof(int));
}
pnumbers[0][1] = 1;
/* Calculating the value of pnumbers[k][l] */
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
/*
if (!(i % 4 == 2 && i != 2))
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
} else if (i > 2) {
for (j = 0; j <= i-1; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
}
*/
}
/* Writing out the triangle */
for (i = 0; i < n; i++) {
for (k = 0; k <= x; k++){
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
x = x-1;
printf("\n");
}
for (i = 0; i < n; i++) {
free(pnumbers[i]);
}
free(pnumbers);
return 0;
}
When I avoid writing to these addresses and just print them out I get some seemingly random integer at these memory addresses.
Also when avoid these addresses and just print out so many rows that I get some spots with a higher integer with more than 3 siphers, it seems to overflow - and I don't see the logic behind it.
The result of running the second code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int factorial(int p) {
if (p>=1) {
return p*factorial(p-1);
}
else {
return 1;
}
}
int NchooseM(int n, int m) {
return factorial(n)/(factorial(n-m)*factorial(m));
}
int main() {
int n =20;
int x = n-2;
int i, j, k;
/*
printf("How many rows of Pascals triangle do you want to write?\n");
scanf("%d", &n);
*/
int **pnumbers;
pnumbers = (int **) malloc(n *sizeof(int *));
/* Allocate memory for storing the individual elements in a row */
for (i = 0; i < n; i++) {
pnumbers[i] = (int *) malloc(i * sizeof(int));
}
pnumbers[0][1] = 1;
/* Calculating the value of pnumbers[k][l] */
for (i = 0; i < n; i++) {
/*
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
*/
if (!(i % 4 == 2 && i != 2))
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
} else if (i > 2) {
for (j = 0; j <= i-1; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
}
}
/* Writing out the triangle */
for (i = 0; i < n; i++) {
for (k = 0; k <= x; k++){
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
x = x-1;
printf("\n");
}
for (i = 0; i < n; i++) {
free(pnumbers[i]);
}
free(pnumbers);
return 0;
}
But row number 13 is still quite messed up.
Code is experiencing int overflow and thus undefined behavior (UB).
With 32-bit int and int factorial(int p), p > 12 oveflows the int range.
Code could use a wider integer type (long long works up to p==20), but improvements can be made at NchooseM() to avoid overflow for higher values.
Something like the below. Works up to int n = 30;
int NchooseM(int n, int m) {
// return factorial(n)/(factorial(n-m)*factorial(m));
int nm = 1;
int den = 1;
for (int i = m+1; i <= n; i++) {
assert(INT_MAX/i >= nm);
nm *= i;
assert(nm % den == 0);
nm /= den++;
}
return nm;
}
Tried unsigned long long and works up to int n = 62;
Edit: Another bug:
I "fixed" by initializing all to 1, yet I suspect something remains amiss in /* Calculating the value of pnumbers[k][l] */ for (i = 0; i < n; i++) { code.
pnumbers[i] = malloc((i + 1) * sizeof pnumbers[i][0]);
for (int j = 0; j < i + 1; j++) {
pnumbers[i][j] = 1;
}
Aside: rather than pnumbers[i] = (int *) malloc((i+1) * sizeof(int));, consider below with no unneeded cast nor trying to match the right type.
pnumbers[i] = malloc(sizeof pnumbers[i][0] * (i+1));

How to efficiently iterate through a base-2 vector

I need to write a program that iterates through all possible combinations for a base-2 (binary) vector. If the size of this vector is 3 you can do this with three nested loops, like this:
bool array[3];
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
for(int k = 0; k < 2; k++)
{
array[0] = i;
array[1] = j;
array[2] = k;
}
}
}
But the problem is that in my application, the array size is variable and can basically be any number. If I'm looking to find all values of a 12-bit vector, I don't want to write 12 nested loops and so it is not maintainable to use the code above. Instead I have come up with the following solution:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#define SIZE 12
int main(void)
{
bool array[SIZE];
for(int i = 0; i < SIZE; i++) array[i] = 1;
int max_num = pow(2, SIZE);
for(int i = 0; i < max_num; i++)
{
if(array[0] == 0) array[0]++;
else
{
array[0] = 0;
for(int j = 1; j < SIZE; j++)
{
if(array[j] == 1) array[j] = 0;
else
{
array[j] = 1;
break;
}
}
}
for(int j = 0; j < SIZE; j++)
{
printf("%d", array[j]);
if(j != SIZE - 1) printf(", ");
else printf("\n");
}
}
}
This still seems as a lot of code to me for such a relatively simple thing. My question is: is there a more efficient way to do this?
What you are doing with the array is effectively incrementing (adding one) to the number represented by the array.
Let's leave the incrementing to the compiler and use bits from the integer.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 12
int main(void)
{
bool array[SIZE];
int max_num = 1 << SIZE;
for(int i = 0; i < max_num; i++)
{
for(int j = 0; j < SIZE; j++)
{
array[j] = (i >> j) & 1;
}
for(int j = 0; j < SIZE; j++)
{
printf("%d", array[j]);
if(j != SIZE - 1) printf(", ");
else printf("\n");
}
}
}
As pointed out by others, it is essentially incrementing a binary number. However, in keeping with the spirit of the original code, I decided not to "cheat" by using native addition/increment operators to increment the vector, and came up with the following:
#include <stddef.h>
#include <stdbool.h>
bool first(size_t size, bool array[size])
{
size_t i;
for (i = 0; i < size; i++)
{
array[i] = 0;
}
return i > 0;
}
bool next(size_t size, bool array[size])
{
size_t i;
for (i = 0; i < size && array[i]; i++)
{
array[i] = 0;
}
if (i < size)
{
array[i] = 1;
return 1;
}
return 0;
}
#include <stdio.h>
int main(void)
{
enum { SIZE = 12 };
bool array[SIZE];
bool going;
for (going = first(SIZE, array); going; going = next(SIZE, array))
{
size_t i;
for (i = 0; i < SIZE - 1; i++)
{
printf("%d, ", array[i]);
}
printf("%d\n", array[i]);
}
return 0;
}
It could be adapted to work in other bases easily:
#include <stddef.h>
#include <stdbool.h>
bool first(size_t size, unsigned int array[size])
{
size_t i;
for (i = 0; i < size; i++)
{
array[i] = 0;
}
return i > 0;
}
bool next(size_t size, unsigned int array[size], unsigned int base)
{
size_t i;
for (i = 0; i < size && array[i] == base - 1; i++)
{
array[i] = 0;
}
if (i < size)
{
array[i]++;
return 1;
}
return 0;
}
#include <stdio.h>
int main(void)
{
enum { SIZE = 5 };
enum { BASE = 3 };
unsigned int array[SIZE];
bool going;
for (going = first(SIZE, array); going; going = next(SIZE, array, BASE))
{
size_t i;
for (i = 0; i < SIZE - 1; i++)
{
printf("%u, ", array[i]);
}
printf("%u\n", array[i]);
}
return 0;
}

What's wrong with the function multiplyTwoMatrices() in this C code for finding fibonacci using matrix multiplication?

#include<stdio.h>
void multiplyTwoMatrices(int (*)[2], int[][2], int[][2]);
void copyMatrix(int[][2], int[][2]);
void powerAMatrix(int[][2], int[][2], int);
int main()
{
int num;
scanf("%d", &num);
int i;
for(i = -1; i <= num; i++)
{
printf("\n%d", fib(i));
}
}
int fib(int num)
{
if(num <= 0)
{
return 0;
}
else
{
int matrix[2][2] = {{1, 1}, {1, 0}};
//int fibMatrix[2][2] = powerAMatrix(matrix[2][2], num);
int fibMatrix[2][2];
powerAMatrix(fibMatrix, matrix, num);
return getFibNum(fibMatrix);
}
}
void powerAMatrix(int fibMatrix[2][2], int matrix[2][2], int num)
{
//fibMatrix = matrix;
copyMatrix(fibMatrix, matrix);
int i = 0;
for(i = 1; i < num; i++)
{
//fibMatrix = fibMatrix * matrix;
multiplyTwoMatrices(fibMatrix, fibMatrix, matrix);
}
}
void copyMatrix(int destinationMatrix[2][2], int sourceMatrix[2][2])
{
int i = 0; int j = 0;
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
destinationMatrix[i][j] = sourceMatrix[i][j];
}
void multiplyTwoMatrices(int multipliedMatrix[2][2], int matrixA[2][2], int matrixB[2][2])
{
int i = 0; int j = 0; int k = 0;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
multipliedMatrix[i][j] = 0; //or just initialize it as a zero matrix.
for(k = 0; k < 2; k++)
{
multipliedMatrix[i][j] += (matrixA[i][k] * matrixB[k][j]);
}
}
}
//working alternative
/*
int x = matrixA[0][0]*matrixB[0][0] + matrixA[0][1]*matrixB[1][0];
int y = matrixA[0][0]*matrixB[0][1] + matrixA[0][1]*matrixB[1][1];
int z = matrixA[1][0]*matrixB[0][0] + matrixA[1][1]*matrixB[1][0];
int w = matrixA[1][0]*matrixB[0][1] + matrixA[1][1]*matrixB[1][1];
multipliedMatrix[0][0] = x;
multipliedMatrix[0][1] = y;
multipliedMatrix[1][0] = z;
multipliedMatrix[1][1] = w;
*/
}
int getFibNum(int fibMatrix[2][2])
{
return fibMatrix[0][1];
}
The function multiplyTwoMatrices() seems to work only if "working alternative" (code closed in comments inside this function) is used instead of the one used currently. I'm unable to understand what is going wrong with this code. A little help is appreciated.
Output expected: 0 0 1 1 2 3 5 8 ...
Output coming: 0 0 1 1 1 1 1 1 ...
while your multiplication function is correct, it doesn't work correctly when the destination is one of the operands; if it is, the operand is changed there while the calculation is underway.
Either require that multipliedMatrix is distinct from both matrixA and matrixB (that'd be preferred), or have a temporary matrix there and copy it into the result!
P.S. it would be much easier wrapping the matrix class into a struct:
struct intmatrix2x2 {
int values[2][2];
};
this would make implicit copies when calling functions; and instead of copyMatrix you can say:
struct intmatrix2x2 b = a;
and your multiplication could read as
struct intmatrix2x2 multiply(struct intmatrix2x2 a, struct intmatrix2x2 b)
{
struct intmatrix2x2 result;
int i = 0; int j = 0; int k = 0;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
result.values[i][j] = 0; //or just initialize it as a zero matrix.
for(k = 0; k < 2; k++)
{
result.values[i][j] += a.values[i][k] * b.values[k][j]);
}
}
}
return result;
}
and you could use it as
struct intmatrix2x2 result = multiply(a, b);

Method returning the wrong value

I'm learning programming in C and C#. This C code is not computing as expected. The method returns the value: -504476904 to the console? What can be the problem here?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int minimum(values)
int values[10];
{
int minimum_value, i;
minimum_value = values[0];
for (i = 1; i < 10; i++)
{
if(values[i] < minimum_value)
{
minimum_value = values[i];
}
}
return (minimum_value);
}
int main()
{
int sumthing[10];
int i;
for (i = 1; i < 10; i++)
{
sumthing[i] = (i * 34);
}
printf("Minimum value of for loop is: %d\n", minimum(sumthing));
return 0;
}
I changed my code to this:
#include <stdio.h>
#include <stdlib.h>
int minimum(values)
int values[10];
{
int minimum_value, i;
minimum_value = values[0];
for (i = 1; i < 10; i++)
{
if(values[i] < minimum_value)
{
minimum_value = values[i];
}
}
return (minimum_value);
}
int main()
{
int sumthing[10];
int i;
for (i = 0; i < 10; i++)
{
sumthing[i] = ((i + 1 )* 34);
}
printf("Minimum value of for loop is: %d\n", minimum(sumthing));
return 0;
}
sumthing[0] is not initialized in your code, since you start looping at index 1 ; that is a first step to correct your program, in the mainfunction :
for (i = 0; i < 10; i++)
{
sumthing[i] = (i * 34);
}
BTW, you're using K&R style. This is considered obsolete.
A more modern implementation of your code, with the above correction ; it seems to be working :
#include <stdio.h>
int minimum(int values[])
{
int minimum_value, i;
minimum_value = values[0];
for (i = 1; i < 10; i++)
{
if(values[i] < minimum_value)
{
minimum_value = values[i];
}
}
return (minimum_value);
}
int main()
{
int sumthing[10];
int i;
for (i = 0; i < 10; i++)
{
sumthing[i] = (i * 34);
}
printf("Minimum value of for loop is: %d\n", minimum(sumthing));
return 0;
}
This syntax is very, very archaic:
/* Don't do this */
int minimum(values)
int values[10];
{
...
/* Do this instead */
int minimum(int values[10])
{
...
Other than that, I looks fine.
I copied/pasted your code, changed "minimum()" to int minimum(int values[10]), ran it ... and got the correct result "34":
Minimum value of for loop is: 34

dynamic 2d matrix implementation

insdead of my static matrix i try to get 2d dynamic matrics
all i want to do is to change the init function so instead of using the defined heigh and width
it would init dynamicaly - please show me the how
void init(int board[][WIDTH], int rows) {
int x, y;
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
board[y][x] = 0;
/* Scatter some live cells: */
board[10][25] = 1;
board[10][26] = 1;
board[10][27] = 1;
board[11][25] = 1;
board[12][26] = 1;
}
int main(void) {
int board[HEIGHT][WIDTH];
init(board, HEIGHT);
..
..
}
this is the code i wanted to use - please show me the right implamintation
without using #define WIDTH 50 #define HEIGHT 20
int **matrix_dyn(int n, int m)
{
int i = 0;
int j = 0;
printf ("please enter the horizontal size of the board \n");
scanf ("%d", &n);
printf ("please enter the vertical size of the board \n");
scanf ("%d", &m);
int **board = (int**)malloc(n * sizeof(int*));
printf("please enter the 0's or 1's to fill the matrix \n");
for (i = 0; i <= n; i++)
board[i] = (int*)malloc(m*sizeof(int));
for(i = 0; i <= n; i++)
{
for(j = 0; j <= m; j++)
scanf ("%d", &board[i][j]);
}
return board;
}
this is all my code:
#include <stdio.h>
#define WIDTH 50
#define HEIGHT 20
void init(int board[][WIDTH], int rows) {
int x, y;
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
board[y][x] = 0;
/* Scatter some live cells: */
board[10][25] = 1;
board[10][26] = 1;
board[10][27] = 1;
board[11][25] = 1;
board[12][26] = 1;
}
void print(int board[][WIDTH], int rows, int cols)
{
int x, y;
char c;
for (y = 0; y < rows; y++) {
for (x = 0; x < cols; x++) {
if (board[y][x] == 1)
printf("X");
else
printf(" ");
}
printf("\n");
}
printf("Press any key to continue:\n");
getchar();
}
int count_neighbors(int board[][WIDTH], int rows,
int y, int x)
{
int i, j;
int result = 0;
for (i = -1; i <= 1; i++)
if ((y+i >= 0) && (y+i < rows))
for (j = -1; j <= 1; j++)
if ((x+j >= 0) && (x+j < WIDTH))
if ((i != 0) || (j != 0))
result += board[y+i][x+j];
return result;
}
int step(int board[][WIDTH], int rows) { // now returns a bool
int x, y;
int neighbors[HEIGHT][WIDTH];
int changed = 0; // save changes
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
neighbors[y][x] = count_neighbors(board, rows, y, x);
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
if (board[y][x] == 1) { /* Currently alive */
if (neighbors[y][x] < 2)
{
board[y][x] = 0; /* Death by boredom */
changed = 1; // change happened
}
else if (neighbors[y][x] > 3)
{
board[y][x] = 0; /* Death by overcrowding */
changed = 1; // change happened
}
}
else { /* Currently empty */
if (neighbors[y][x] == 3)
{
board[y][x] = 1;
changed = 1; // change happened
}
}
return changed; // return the status (changed yes/no?)
}
int main(void) {
int board[HEIGHT][WIDTH];
init(board, HEIGHT);
while (1) {
print(board, HEIGHT, WIDTH);
if(step(board, HEIGHT) == 0) // no change
break; // leave the loop
}
return 0;
}
Declare & allocate board like so:
int *board = malloc( n * m * sizeof(int) );
Then, anytime you wish to access board[x][y], use the following expression:
board[y*n+x]
Try using a struct, heres a simple implementation I wrote up (compiled using GCC, to support the constructor attribute.
// IntGrid.h
typedef struct intGrid_t {
int **data;
int rows;
int cols;
} *IntGridRef;
struct {
IntGridRef(* create)(int, int);
void (* print)(IntGridRef);
void (* free)(IntGridRef);
int **(* data)(IntGridRef);
int (* rows)(IntGridRef);
int (* cols)(IntGridRef);
} IntGrid;
// IntGrid.c
IntGridRef _intGrid_create(int rows, int cols);
void _intGrid_print(IntGridRef this);
void _intGrid_free(IntGridRef this);
int **_intGrid_data(IntGridRef this);
int _intGrid_rows(IntGridRef this);
int _intGrid_cols(IntGridRef this);
__attribute__((constructor))
static void intGrid_setup()
{
IntGrid.create = _intGrid_create;
IntGrid.print = _intGrid_print;
IntGrid.free = _intGrid_free;
IntGrid.data = _intGrid_data;
IntGrid.rows = _intGrid_rows;
IntGrid.cols = _intGrid_cols;
}
IntGridRef _intGrid_create(int rows, int cols)
{
IntGridRef this = calloc(1, sizeof(struct intGrid_t));
this->rows = rows;
this->cols = cols;
this->data = calloc(rows, sizeof(int *));
for (int i = 0; i < rows; i++) {
this->data[i] = calloc(cols, sizeof(int *));
}
return this;
}
void _intGrid_print(IntGridRef this)
{
printf("{\n");
for (int i = 0; i < this->rows; i++) {
printf(" { ");
for (int j = 0; j < this->cols; j++) {
printf("%i", this->data[i][j]);
if (j != this->cols - 1)
{
printf(", ");
}
}
printf(" }\n");
}
printf("}\n");
}
void _intGrid_free(IntGridRef this)
{
for (int i = 0; i < this->rows; i++) {
free(this->data[i]);
}
free(this->data);
free(this);
}
int **_intGrid_data(IntGridRef this)
{
return this->data;
}
int _intGrid_rows(IntGridRef this)
{
return this->rows;
}
int _intGrid_cols(IntGridRef this)
{
return this->cols;
}
Example Usage:
int main(int argc, char *argv[])
{
IntGridRef grid = IntGrid.create(10, 10);
for (int i = 0; i < IntGrid.rows(grid); i++) {
for (int j = 0; j < IntGrid.cols(grid); j++) {
IntGrid.data(grid)[i][j] = arc4random_uniform(10);
}
}
IntGrid.print(grid);
IntGrid.free(grid);
return 0;
}
You're basically there, but instead of having the compiler generate code to map [x][y] to a specific element in the memory allocated for board, you have to do the mapping yourself: board[x*h+y] or board[y*w+x] (where w is width & h is height); it doesn't matter which you choose, just be consistent (a function or macro would help here).

Resources