Why are my array elements getting overridden? - c

I stared at this code for at least 4 hours.
I'm not sure what I'm doing wrong.
I'm updating the array hand[5][2] with a simple for loop.
The values stored in hand[0][2], hand[0][3] and hand[0][4] keep getting overwritten.
I used the debugger to go slowly through every single line but I still don't
understand why I'm getting different values.
This is the output I'm getting
hand[0][0] = 0
hand[0][1] = 1
hand[0][2] = 2
hand[0][3] = 3
hand[0][4] = 4
hand[1][0] = 0
hand[1][1] = 1
hand[1][2] = 2
hand[1][3] = 3
hand[1][4] = 4
0 1 0 1 2 // WHY ARE hand[0][2],hand[0][3],hand[0][4] not the same????
0 1 2 3 4
Code:
int main() {
//tests();
int hand[5][2];
int a[5], b[5];
char line[100];
int player = 0;
int card = 0;
for (int i = 0; i < 10; i++) {
hand[player][card] = card;
printf("hand[%d][%d] = %d\n", player, card, hand[player][card]);
card++;
if (card == 5) { player++; card = 0; }
}
// print first hand
for (int j = 0; j < 5; j++) {
printf("%d ", hand[0][j]);
}
printf("\n");
// print second hand
for (int j = 0; j < 5; j++) {
printf("%d ", hand[1][j]);
}
printf("\n");
return 0;
}

int hand[5][2]; should be int hand[2][5];

Related

Unwanted array update when updating a variable in C

I'm trying to convert an int to char with sprintf.
for(int i=0; i<n; i++){
char buffer[100];
load = group[i];
int num = pow(10, (load-1));
for(int j=(load-2); j>=0; j--){
num+=pow(10, j);
}
sprintf(buffer,"%d",num);
(...)
When I print buffer, everything seems alright, as I just want it to be a string there.
Then, I want to store it inside an array. Specifically here:
typedef struct Unario {
char * bits ;
} Unario ;
But when trying to store buffer inside the next index of the array, all the rest of the variables saved before, update to the new buffer definition.
Here's the full function:
Unario * comprimir_en_unario ( int n, int * grupo ){
int load;
int j = 0;
int SIZE = n*2;
Unario * comprimiendo = malloc(SIZE * sizeof(comprimiendo));
for(int i=0; i<n; i++){
char buffer[100];
load = grupo[i];
printf("\ngrupo[%d] = %d\n", i, load);
int num = pow(10, (load-1));
for(int j=(load-2); j>=0; j--){
num+=pow(10, j);
}
sprintf(buffer,"%d",num);
comprimiendo[j].bits = buffer;
j++;
comprimiendo[j].bits = "0";
j++;
}
for(int i=0; i<SIZE; i++){
printf("in %d = %s\n", i, comprimiendo[i].bits);
}
return comprimiendo;
};
With the following input:
int m[6] = {8,2,8,8,2,3};
and following unwanted output:
in 0 = 111
in 1 = 0
in 2 = 111
in 3 = 0
in 4 = 111
in 5 = 0
in 6 = 111
in 7 = 0
in 8 = 111
in 9 = 0
in 10 = 111
in 11 = 0
and the one I'm trying to get:
in 0 = 11111111
in 1 = 0
in 2 = 11
in 3 = 0
in 4 = 11111111
in 5 = 0
in 6 = 11111111
in 7 = 0
in 8 = 11
in 9 = 0
in 10 = 111
in 11 = 0
Side note: I can't change the struct nor delete it because its a part of a group of structs.
Because your the bits in your struct can not store values, it is only a pointer
So you have to make sure each time you have stored your stirng somewhere
In your used function, each time you use sprintf, the stored value in buffer will be refreshed
In that case, your final output must be the lastest value of buffer
It means, if you changed the array from { 8,2,8,8,2,3 } to { 8,2,8,8,2,4 }, the final output will be all in 1111(the lastest value of buffer)
Here is one way to save it, I used 2d array to store the string
Unario * comprimir_en_unario(int n, int * grupo)
{
int load;
int j = 0;
int SIZE = n * 2;
Unario * comprimiendo = (Unario *)malloc(SIZE * sizeof(Unario));//No need to change.
char buffer[100][100];//Use 2d array to store the string each time
for (int i = 0; i < n; i++)
{
load = grupo[i];
printf("grupo[%d] = %d\n", i, load);
int num = pow(10, (load - 1));
for (int j = (load - 2); j >= 0; j--)
{
num += pow(10, j);
}
sprintf(&buffer[i][0], "%d", num);//Related changes
comprimiendo[j].bits = &buffer[i][0];//Related changes
j++;
comprimiendo[j].bits = "0";
j++;
}
for (int i = 0; i < SIZE; i++)
{
printf("in %d = %s\n", i, comprimiendo[i].bits);
}
return comprimiendo;
}
You may find more solutions after you noticed the problem of your origional function

variable in for loop has different values in the same loop (C language)

In these loops i has two different values and I don't know why it's that, as I'm not increasing it's size. I'm printing i in both loops, but it has a greater value when printed inside the inner loop and the value it should have in the extern one.
Edit: the description erased, I rewrote it with only relevant information.
Can you tell me why this happens?
int position = 0;
int size = 4;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < position; j++)
{
printf(" i = %d\n", i);
}
position++;
printf("i = %d\n", i);
}
printf("\n");
This is what it prints:
i = 0
i = 1
i = 1
i = 2
i = 2
i = 2
i = 3
i = 3
i = 3
i = 3
While the desired output should be:
i = 0
i = 1
i = 1
i = 2
i = 2
i = 2
i = 3
i = 3
i = 3
i = 3
To get code in a loop executed atleast once, you could use a do-while-loop. I went ahead and changed it for you. Additionally, printing an unindented i before the loop gets you to your desired output.
int position = 0;
int size = 4;
for (int i = 0; i < size; i++)
{
printf("i = %d\n", i);
int j = 0;
do {
printf(" i = %d\n", i);
j++;
} while (j < position);
position++;
}
printf("\n");
Edit: Ah, I see, you have changed your desired output yet again! This makes the condition of executing the code atleast nolonger necessary. A regular while-loop does the trick:
int position = 0;
int size = 4;
for (int i = 0; i < size; i++)
{
printf("i = %d\n", i);
int j = 0;
while (j < position) {
printf(" i = %d\n", i);
j++;
}
position++;
}
printf("\n");
It's because you've created an odd variable loop condition with position. First lap in the i for loop, it skips the inner loop, then increases position by 1 and prints i = 0. Then next lap when i is 1, it executes the inner loop, and so on.
This would be why it is a bad idea to use an ever-changing condition in for loops - it makes the code much harder to understand.
Just place the output of the variable i before the inner loop.
#include <stdio.h>
int main(void)
{
int position = 0;
int size = 4;
for (int i = 0; i < size; i++)
{
printf("i = %d\n", i);
for (int j = 0; j < position; j++)
{
printf(" i = %d\n", i);
}
position++;
}
printf("\n");
return 0;
}
The program output is
i = 0
i = 1
i = 1
i = 2
i = 2
i = 2
i = 3
i = 3
i = 3
i = 3

how to check if a matrix has the same value in a row or column in C

I have a homework problem. It requires us to make a matrix based on user's input. For example : if user input 4 so the matrix will be 4 X 4. After that, the program will check if the matrix has the same value in a row or column. and it will give yes or no output.
For example :
input :
2
1 2
2 1
Output :
Yes
(because that matrix doesnt has a same value in a row or a column.)
Input 2 :
3
4 5 6
7 8 9
7 3 3
Output :
No
(Because that matrix have same values in a row or column (3 & 3 and 7 & 7)
Input 3:
2
1 2
3 2
Output :
No
(because that matrix have same value on column 1.)
Input 4
2
1 1
3 4
Output :
No
(because that matrix has same value in first row(1 1)
I have tried to do that, but some 'cases' still doesnt work. For example, i tried to include a count in my code but some of the count is not true.
example :
input :
4
3 4 5 6
2 3 4 5
6 5 6 3
5 4 6 3
OUTPUT :
No
count : 2
(it supposed to be 3 because it has the same value which are 6 (on row 3), 6 on column 3, and 3 on column 4.)
#include "stdio.h"
int main()
{
int matrix[500][500];
int testcase;
int count = 0;
scanf("%d",&testcase); getchar();
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
scanf("%d",&matrix[i][j]); getchar();
}
}
// printf("[0,0] = %c",matrix[0][0]);
// printf("\n[0,1] = %c",matrix[0][1]);
// printf("\n[1,0] = %c",matrix[1][0]);
// printf("\n[1,1] = %c",matrix[1][1]);
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
if(matrix[i][j] == matrix[i][j+1]) {
count = count + 1;
}
else if(matrix[i][j] == matrix[i+1][j]) {
count = count + 1;
}
}
}
if(count > 0) {
printf("No\n");
} else{
printf("Yes\n");
}
printf("Count : %d\n",count );
getchar();
return 0;
}
As I see you check if 2 numbers of the same value differ only one column or one row here:
if(matrix[i][j] == matrix[i][j+1]) {
count = count + 1;
}
else if(matrix[i][j] == matrix[i+1][j]) {
count = count + 1;
}
I think that you might need a temp variable so that you can scan each line and then each column separately , for example:
temp = matrix[i][j];
if(checkRow(temp, i, j, matrix, testcase) == true) count++;
if(checkColumn(temp, i, j, matrix, testcase) == true) count++;
and the checkRow would be something like this:
bool checkRow(int temp, int row, int col, int matrix[][500], int size)
{
for(int i=col; i < size;)
{
if(temp == matrix[row][i]) return true;
}
return false;
}
and respectively you will build the checkColumn function.
EDIT:
Since you told me you haven't learned how to use functions yet, this would be your final program. It works and I might suggest that the final test case should output "count = 4" since there is a case that you might missed.
Here is the code:
#include "stdio.h"
int main()
{
int matrix[500][500];
int testcase;
int count = 0;
scanf("%d",&testcase); getchar();
int temp;
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
scanf("%d",&matrix[i][j]); getchar();
}
}
// printf("[0,0] = %c",matrix[0][0]);
// printf("\n[0,1] = %c",matrix[0][1]);
// printf("\n[1,0] = %c",matrix[1][0]);
// printf("\n[1,1] = %c",matrix[1][1]);
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
temp = matrix[i][j];
//Scan current row
for(unsigned k = j+1; k < testcase; k++)
{
if(temp == matrix[i][k])
{
count++;
break;
}
}
//Scan current column
for(unsigned k = i+1; k < testcase; k++)
{
if(temp == matrix[k][j])
{
count ++;
break;
}
}
}
}
if(count > 0) {
printf("No\n");
} else{
printf("Yes\n");
}
printf("Count : %d\n",count );
getchar();
return 0;
}
May I suggest that before you copy the code you must understand the algorithm that lies behind it. It's simple and brute force thinking.

How to print the amount of same integers that my 2 arrays have? [C]

I have problem with my code I need to make. I have to take 14 parameters from command line and use them to make lottery numbers, winning numbers and then compare those 2 with each other.
For example using this parameter: ./a.out 2 30 17 8 6 19 24 7 6 1 2 3 5 4
Should make something like this:
Winning numbers: 2 30 17 8 6 19 24
Lottonumbers: 7 6 1 2 3 5 4
2 are the same: 6 2
My code is almost working as intended, but I can't seem to print this right: 2 are the same. It always loops like this: 1 are the same: 6 2 are the same: 2.
Number 2 is the amount of same numbers that are found when 2 arrays are compared. My question is how can I print it so that it won't duplicate the text and with the right amount? My head can't seem to work even if it's so simple :/
#include <stdio.h>
#include <stdlib.h>
int main(int args, char **argv)
{
int i;
int winningNumbers[7];
int lottoNumbers[7];
int j;
int a;
int b;
int winningNumber;
int lottoNumber;
int count = 0;
printf("Winning numbers: ");
for (i=0;i<7; i++) {
winningNumber = atoi(argv[i+1]);
winningNumbers[i] = winningNumber;
printf("%d ", winningNumber);
}
printf("\n");
printf("Lotto numbers:: ");
for (j= 8; j < args; j++) {
lottoNumber = atoi(argv[j]);
lottoNumbers[j-8] = lottoNumber;
printf("%d ", lottoNumber);
}
printf("\n");
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
printf("%d are the same: %d", count, winningNumbers[b]);
}
}
}
return 0;
}
Searching for matches and displaying the result are two separate tasks. It is simpler and more flexible not to attempt to do them at the same time.
First search for the matches and store them in an array. Then display the content of the array however you want.
int main (int argc, char *argv[])
{
int winningNumbers[7];
int lottoNumbers[7];
int commonNumbers[7];
int count = 0;
// fill winningNumbers
// fill lottoNumbers
// NOTE: the following loop assumes that in both arrays
// no number is repeated.
// You should check that this is indeed the case.
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (lottoNumbers[i] == winningNumbers[j]) {
commonNumbers[count] = lottoNumbers[i];
count++;
}
}
}
printf ("%d are the same:", count);
for (int i = 0; i < count; i++) {
printf (" %d", commonNumbers[i]);
}
printf ("\n");
return 0;
}
Many simple programs should follow this structure:
read and check input
transform input to output
print output
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
}
}
printf("%d are the same: ", count);
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
printf(" %d", winningNumbers[b]);
}
}
printf("\n");
int finalArray[7];
int i;
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
finalArray[count] = lottoNumbers[a];
count = count + 1;
}
}
}
printf("%d are same: ", count);
for(i = 0; i < count; i++)
printf("%d ", finalArray[i]);

Printing 2 dimensional array of pointers to structs

I have been doing homework yesterday, I have done most of it, but couldn't make the main thing. I don't know why it's not working I have asked other students, but nobody knows what's the problem. Basically this program is a small game, there are 18 players 9 on each team. the program randomly gives players coordinates and directions and they start to move. I have basically done the program, but I have problem with field, It doesn't show the players at all.
I tried many things and when testing noticed that it doesn't print even testing string in the if statement I wrote. when I write this part field[i][j] = &players[k][0]; I have checked if field[i][j] really gets the x and y coordinate and yes it does. but in the print_field class it takes field[][] as null and the field is empty. players is an array of structs. field is an array of pointers that point to players or NULL.
I have tried with all of my knowledge and couldn't make any better.
What is wrong with this code? Why isn't it showing the players on the field?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define LENGTH 25
#define WIDTH 25
enum direction {Right, Left, Up, Down}; /*Right = 0, Left = 1, Up = 2, Down = 3*/
void print_field();
void random_positions();
void playerdirection();
void motion();
void game();
struct player
{
char *dora;
char *team;
char *name; //string?
int x,y; //coordinates
int direction;
};
typedef struct player Player;
struct player *field[WIDTH][LENGTH];
Player players[8][1];
int main()
{
srand (time(NULL));
int i; //players 9 in each team team1 = 0 team2 = 1
players[0][0].name = "A1";
players[1][0].name = "A2";
players[2][0].name = "A3";
players[3][0].name = "A4";
players[4][0].name = "A5";
players[5][0].name = "A6";
players[6][0].name = "A7";
players[7][0].name = "A8";
players[8][0].name = "A9";
players[0][1].name = "B1";
players[1][1].name = "B2";
players[2][1].name = "B3";
players[3][1].name = "B4";
players[4][1].name = "B5";
players[5][1].name = "B6";
players[6][1].name = "B7";
players[7][1].name = "B8";
players[8][1].name = "B9";
for(i = 0; i < 9 ; i++)
{
players[i][0].team = "Team A";
players[i][1].team = "Team B";
players[i][0].dora = "Alive";
players[i][1].dora = "Alive";
}
random_positions();
playerdirection();
print_field();
motion (Player player);
print_field();
game();
return 0;
}
void random_positions()
{
int i,j,k;
int xs[17],ys[17];
for(i= 0; i<9 ; i++)
{
players[i][0].x = rand() % 25;
players[i][0].y = rand() % 25;
players[i][1].x = rand() % 25;
players[i][1].y = rand() % 25;
printf("A%d x = %d y = %d \n",i+1,players[i][0].x,players[i][0].y);
printf("B%d x = %d y = %d \n",i+1,players[i][1].x,players[i][1].y);
}
for(i = 0; i < 9 ; i++)
{
xs[i] = players[i][0].x;
xs[i+8] = players[i][1].x;
ys[i] = players[i][0].y;
ys[i+8] = players[i][1].y;
for(j = 0; j <= i ; j++)
{
//printf("j%d start\n",j);
if(i != j && xs[i] == xs[j])
{
//printf("i%d start\n",j);
if(ys[i] == ys[j])
{
return random_positions();
}
//("j%d done\n",j);
}
//printf("j%d done\n",j);
}
}
for(i = 0; i < 25; i++)
{
for(j = 0; j < 25; j++)
{
for(k = 0; k < 9; k++)
{
if(i == players[k][0].x && j == players[k][0].y)
{
field[i][j] = &players[k][0];
}
if(i == players[k][1].x && j == players[k][1].y)
{
field[i][j] = &players[k][1];
}
else field[i][j] = NULL; //I da J sheidzleba shesacvleli iyos
}
}
}
}
/*this function prints out the given state of the field*/
void print_field(){
int i,j;
printf("\n");
printf("|0 1 2 3 4 5 6 7 8 9 101112131415161718192021222324|\n"); /*just to show easier the allignment*/
for(j=0; j<WIDTH+2; j++) /*This first loop goes through row and creates them each by each*/
{
if(j == 0 || j == WIDTH +1) /*creates the upper and lower part of the field*/
for(i=0; i<LENGTH+2; i++) /*there should be space for frame so I added 2 to LENGTH in the loop*/
{
if(i==0)
printf("-");
else if(i == LENGTH+1)
printf("-\n");
else printf("--"); /*3 decimals*/
}
else
for(i=0; i<LENGTH+2; i++) /*Goes through the columns in this row and creates either frame or puts the nodeid*/
{
if(i==0)printf("|"); /*frame*/
else if(i == LENGTH+1) printf("| %d\n",(j-1)); /*frame*/
else if(field[j-1][i-1] != NULL)
{
printf("aaa");
printf("%-*s",2,(*field[j-1][i-1]).name); /*putting nodeid 3 decimals*/
}
else printf(" ");
}
}
printf("\n");
}
You need Player[9][2] instead of Player[8][1]. You should initialize an array with its length although you could only access index up to length - 1 because arrays are indexed from 0.

Resources