Setting 2D Integer Array values all to 0 in C - c

I am trying to set all the values in my 2D array to 0 and then print all the scores back to make sure they are correct.
struct Game {
int GameScoresHome[10][10];
};
int main() {
struct Game game;
memset(game.GameScoresHome, 0, sizeof game.GameScoresHome);
for (int x=0;x<100;x++) {
int y = floor(x/10);
printf("%d ",game.GameScoresHome[x][y]);
}
return 0;
}
The current output is:
0 0 0 0 0 0 0 0 0 0 0 0 822083893 32767 32767 32767 32767 32767 32767 1651067951 1634028652 1345283180 1702057263 1701080931 2054842477 1866870631 1885417061 1647262318 1146113364 896624241 1280918623 1919052108 1819042146 1818850626 1634956149 1852133983 1264923239 792545364 1666723698 1836345960 1163089152 1949263220 1919250021 1868774725 1213481296 796026224 1785230711 1650803759 792546380 1213481296 1868781615 1752003690 6780258 1497628720 778396783 1920232291 792545364 1666723698 1836345960 1735746149 796026224 1785230711 1650803759 0 0 3 0 7 0 -2147482624 0 0 0 0 0 0 0 0 0 0 233472 1869045599 48 1868783455 5312 1633967967 3480 1818320735 304 1919115103 0 1852796269 0 115 0 72 0 1227 0 0
The first 11 zeros are as they should be then it all goes wrong. What's going on?

You're accessing memory outside the array.
Your x variable iterates from 0 to 99.
for (int x=0;x<100;x++)
But your array has only 10 rows.
int GameScoresHome[10][10];
One fix would be to use simple nested loops.
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
}
Nested loops would also make it easy to include a newline after each row.
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
printf("\n");
}

In your code
for (int x=0;x<100;x++) {
int y = floor(x/10);
printf("%d ",game.GameScoresHome[x][y]);
}
the x value is going out of bound. Maybe you want to take a %10 value of x and change the index locations, like
printf("%d ",game.GameScoresHome[y][x%10]);
or, use a nested loop to maintain two indexes separately.

What about?
struct Game game = {.GameScoresHome = {0}};
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
printf("\n");
}

Write the loop simpler
for ( int x = 0; x < 100; x++) {
printf("%d ",game.GameScoresHome[x / 10][x % 10]);
}
or
for ( int x = 0; x < 100; x++) {
printf("%d ",game.GameScoresHome[x / 10][x % 10]);
if ( x % 10 == 9 ) printf( "\n" );
}
As for your loop then x is being changed from 0 up to 100 and as result using x as the first index in the statement
printf("%d ",game.GameScoresHome[x][y]);
^^^
is invalid. And y is calculated incorrectly.

Related

put first array index at the end of array

I have an array called int arr[10] = {1,2,3,4,5}
From my understanding the rest of the array is filled with 0's.
My questions is if its a fixed array length how can I put the first index behind the last index that is not a 0. For example
I believe the 0 is not shown in real printf but I am including it for illustration purposes
for (int i = 0 ; i < 10 ; i++)
{
print("%i" , arr[i]);
}
The output
1 2 3 4 5 0 0 0 0 0
If i move the first index to the back of the 5 like so
for (int i = -1 ; i < 10 ; i++)
{
arr[i] = arr[i + 1];
print("%i" , arr[i]);
}
Will the output put the 1 behind the 5 or at the back of the whole array?
2 3 4 5 1 0 0 0 0 0
or because there is 0s then
2 3 4 5 0 0 0 0 0 1
If my question is unclear please tell me and I will try explain it.
The output
1 2 3 4 5 0 0 0 0 0
No, the actual output is
1234500000
Your code has undefined behavior. The first iteration of the loop (with i = -1) tries to assign to arr[-1], which does not exist:
arr[i] = arr[i + 1];
Similarly, the last iteration (with i = 9) tries to read from arr[10], which also does not exist.
I'm not sure why you think your code will move the first element back.
From my understanding the rest of the array is filled with 0's
You are right.:)
If i move the first index to the back of the 5 like so
for (int i = -1 ; i < 10 ; i++)
{
arr[i] = arr[i + 1];
print("%i" , arr[i]);
}
then you will get undefined behavior because the indices -1 and 10 are not valid indices.
It seems what you are trying to do is the following
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { N = 10 };
int a[N] = { 1, 2, 3, 4, 5 };
size_t pos = 0;
while ( pos < N && a[pos] != 0 ) ++pos;
if ( pos != N && !( pos < 3 ) )
{
int tmp = a[0];
pos -= 2;
memmove( a, a + 1, pos * sizeof( int ) );
a[pos] = tmp;
}
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
return 0;
}
The program output is
2 3 4 1 5 0 0 0 0 0

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.

Print two-dimensional array with a function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
void printBoard(int board[8][8])
{
int i,j;
for(i = 0; i<8; i++)
{
for(j = 0; j<8; j++)
{
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int main(){
int i, j;
int board[8][8];
for(i = 0; i<8; i++)
{
for(j = 0; j<8; j++)
{
scanf("%d", &board[i][j]);
}
}
printBoard(board);
Why does the following void function not print the two dimensional array? It just continues asking for input. I tried it without the function as well, and it still doesn't work.
We were meant to use this as part of our homework assignment. Can someone please explain how to get around this?
Your main is looping through scanf which is a function that asks for user input 64 times. You need to input 64 values before the printBoard() statement is reached.
First of all your printBoard function doesn't print all array.
When you fix this (first loop in function 8 instead of 2) you get what you want but i suggest try on smaller array, since you need to put 64 values.
In nested loops, the inner loop will execute to completion for every time that the outer loop executes. This means that scanf will be called 8 * 8 = 64 times. scanf takes an input from the console, so that means you will have to input 64 values into the console before they are printed.
Maybe try reducing the size of the array from 8 * 8 to something more manageable, like 3 * 3 or 4 * 4 -- that way you don't have to spend a minute or two punching in numbers just to test it.
#include<stdio.h>
void printBoard(int board[8][8]);
int main(){
int i, j;
int board[8][8];
for(i = 0; i<8; i++)
{
for(j = 0; j<8; j++)
{
scanf("%d", &board[i][j]);
}
}
return 0;
}
void printBoard(int board[8][8])
{
int i,j;
for(i = 0; i<8; i++)
{
for(j = 0; j<8; j++)
{
printf("%d ", board[i][j]);
}
printf("\n");
}
}
In your i for loop it is row and j loop is column so loop will 8 row and 8 columns so it will run 64 times, then it take 64 inputs and after scanf will complete.
So I was inputting my values like this to begin with:
00000000
00100000
00001000
00001010
01010000
00020000
00000000
00000000
Which didn't seem to work.
Then, I tried:
0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0
0 1 0 1 0 0 0 0
0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
and it worked. I guess it counted 64 individual values this way.
Thanks!

Find maximum users in a cell of a matrix of size nxn

I was solving this algorithm problem but i am unable to find the reference answer as provided. Any help or tip in solving this problem is appreciated.
The problem statement is as follows
In an area of size NxN each cell contains 1 at time T=0 where 1 represent one user.
Hence, at T= 0 and N = 5 the matrix is as below
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Each cell is a user.
Now at time T =1,2,3 etc the position of each user changes.
if x(row)+y(col) = even
New x = (x+y)^2%N
New y = (x*y)%N
if x(row)+y(col) = odd
New x = (x+y)%N
New y = |x-y|%N
Find the maximum users at time T = 3
Reference, for N=5 and T= 3 Max users in a cell should be 8.
I have tried solving this problem but I always end up with 11 as my max if I move all the users and 6 if I move just 1 user every time.
Any tips where I might be going wrong in understanding or solving this problem is very much appreciated. Thank you.
Below is my code which I used for solving this problem
Its in C programming language. Thanks in advance.
int abs(int y, int x)
{
int temp = x - y;
return temp > 0 ? temp : -temp;
}
int new_x(int x, int y, int n)
{
if((x+y)%2)
return (((x+y)*(x+y))%n);
else
return (x+y)%n;
}
int new_y(int x, int y, int n)
{
if((x+y)%2)
return (x*y)%n;
else
return ((abs(x,y))%n);
}
void print_matrix(int *p, int n, int time)
{
int i,j;
int sum = 0;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%d\t",*((p+i*n)+j));
sum += *((p+i*n)+j);
}
printf("\n");
}
printf("Sum = %d\t at T=%d\n",sum, time);
}
int main(void)
{
int T = 3;
int N = 5;
int test_case,i,j,x,y,item, sum, val;
int arr_initial[5][5];
//====================================
//For Time T=0 all elements are 1
//====================================
for(i=0;i<N;i++){
for(j=0;j<N;j++) {
arr_initial[i][j] = 1;
}
}
//=====================================
printf("Initial Matrix at T0 time\n");
print_matrix((int*)arr_initial, N, 0);
printf("\n");
//====================================
//Now calculate the new position for Time T1,T2 & T3
//====================================
for(test_case =1; test_case<=T;test_case++)
{
sum = 0;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{//Get NewX and NewY for movement
x = new_x(i,j,N);
y = new_y(i,j,N);
if(x==i && y==j)
{
//No movement as initial and new position is same
}
else{
//There is a movement
item = arr_initial[i][j];
val = item -1;
if(val<0)
{
//no item to move
}
else
{
arr_initial[x][y] += arr_initial[i][j];
arr_initial[i][j] = 0;
}
}
}
}
//=======================================================
printf("\n");
printf("Matrix at Time T = %d\n",test_case);
print_matrix((int*)arr_initial, N, test_case);
printf("\n");
}
return 0;
}
Your task statement differs from the code - you say (x*y)^2 but implement (x+y)^2. This solution works by building the next generation in a separate array.
#include <stdio.h>
#include <string.h>
#include <math.h>
#define N 5
int main(void) {
char matrix[N][N], next[N][N];
int x, y, t, x2, y2, max;
memset(matrix, 1, sizeof(matrix)); // initialise matrix
for(t=0; t<3; t++) {
memset(next, 0, sizeof(next)); // clear next generation
for (y=0; y<N; y++)
for (x=0; x<N; x++) {
if ((x + y) % 2 == 0) {
x2 = ((x + y) * (x + y)) % N;
y2 = (x * y) % N;
} else {
x2 = (x + y) % N;
y2 = abs(x - y) % N;
}
next[y2][x2] += matrix[y][x];
}
memcpy(matrix, next, sizeof(matrix)); // copy back
}
max = 0;
for (y=0; y<N; y++) { // print matrix
for (x=0; x<N; x++) {
if (max < matrix[y][x])
max = matrix[y][x];
printf("%-3d", matrix[y][x]);
}
printf ("\n");
}
printf ("Max is %d\n", max);
return 0;
}
Program output:
1 0 0 0 0
0 2 0 0 4
0 0 0 0 0
4 8 0 4 0
0 2 0 0 0
Max is 8
1) You calculate if (x+y) is odd wrongly. If (x+y)%2 is true than x+y is odd. Therefore:
int new_x(int x, int y, int n)
{
if((x+y)%2)
return (((x+y)*(x+y))%n);
else
return (x+y)%n;
}
int new_y(int x, int y, int n)
{
if((x+y)%2)
return (x*y)%n;
else
return ((abs(x,y))%n);
}
should be changed to:
int new_x(int x, int y, int n)
{
if((x+y)%2)
return (x+y)%n;
else
return (((x+y)*(x+y))%n);
}
int new_y(int x, int y, int n)
{
if((x+y)%2)
return ((abs(x,y))%n);
else
return (x*y)%n;
}
2) You change fields in array, that were possibly still not processed:
arr_initial[x][y] += arr_initial[i][j];
You need to use another matrix, initialized to 0, to track new values in it and copy changes back to original matrix at the end of each step.
The problem is that you are reading the value from the array and the value might already be modified, which becomes the value for T + 1!
Thus, you need another array to keep track of the value for T. Here is the idea:
for(i = 0; i < N; i ++)
for (j = 0; j < N; j ++)
alter_arr[i][j] = current_arr[i][j];
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{//Get NewX and NewY for movement
x = new_x(i,j,N);
y = new_y(i,j,N);
printf("%d, %d moved to %d, %d\n", i, j, x, y);
if(x==i && y==j)
{
// no movement
}
else{
//There is a movement
item = current_arr[i][j];
val = item -1;
if(val<0)
{
//no item to move
}
else
{
alter_arr[x][y] += current_arr[i][j];
alter_arr[i][j] -= current_arr[i][j];
}
}
}
}
int (*tmp)[5] = current_arr;
current_arr = alter_arr;
alter_arr = tmp;
//=======================================================
printf("\n");
printf("Matrix at Time T = %d\n",test_case);
And change the if statement in your new_x and new_y function.
Below is the result, the max is 8 at T = 3:
Initial Matrix at T0 time
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Sum = 25 at T=0
Matrix at Time T = 1
1 2 0 2 0
2 2 0 4 2
0 2 0 0 0
0 2 0 2 0
2 2 0 0 0
Sum = 25 at T=1
Matrix at Time T = 2
1 0 0 4 0
2 4 0 6 2
0 0 0 0 0
0 2 0 2 0
0 2 0 0 0
Sum = 25 at T=2
Matrix at Time T = 3
1 0 0 4 0
0 2 0 8 2
0 0 0 0 0
0 0 0 4 0
0 4 0 0 0
Sum = 25 at T=3

Storing subsets of a array

this program is "calculating" all subsets of the array source. I need to store the resulting values in another 2D filed named polje. If I just use the printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); the code works fine but something fails when it is trying to copy everything into the resulting field. I suppose I am dogin something wrong in the indexing of the array polje.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int f;
int i,j;
int source[2][3] = {{0,3,5},{3,4,2}};
int currentSubset = 3;
int polje[8][3];
for(i=0;i<8;i++){
for(j=0;j<3;j++){
polje[i][j]=0;
}}
int tmp;
while(currentSubset)
{
tmp = currentSubset;
for( i = 0; i<3; i++)
{
if (tmp & 1)
{
printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); //writes out everything I want
polje[currentSubset][0]=source[i][0];
polje[currentSubset][1]=source[i][1];
polje[currentSubset][2]=source[i][2];
}
tmp >>= 1;
}
printf("\n");
currentSubset--;
}
for(i=0;i<8;i++){
for(j=0;j<3;j++){
printf("%d ", polje[i][j]);
}printf("\n");}
return (EXIT_SUCCESS);
}
The output field should be:
0 3 5
3 4 2
3 4 2
0 0 0
0 3 5
0 0 0
0 0 0
0 0 0
But instead it is:
0 3 5
3 4 2
3 4 2
0 0 0
*0 0 0*
0 0 0
0 0 0
0 0 0
tmp is a bit mask with only two bits, so the inner loop should be for ( i = 0; i < 2; i++ ).
Also the correct index into the polje array is polje[currentSubset * 2 + i][0] since each subset in polje takes two spaces and i is either 0 or 1.
I think you just have a logic error. Your loop's skeleton is:
currentSubset = 3;
while ( currentSubset )
{
// ...
polje[currentSubset][...] = ...;
// ...
currentSubset--;
}
So you never write to any rows except the first three.

Resources