Home > Back-end >  Am I initializing correctly the state of a matrix in C language?
Am I initializing correctly the state of a matrix in C language?

Time:01-31

I'm simulating a square surface that "traps" molecules in C and, I don't know if it's correctly initialized. I want in the beginning of the whole simulation that the grid is totally empty (without any molecule on it) so that it can start to trap the mentioned molecules.

But, when I generate randomly the coordinates of an entry and start checking if the lattice is empty ( to attempt adding molecules to it later on), it seems that every entry the program choose is already "occupied" and I can't see why since I haven't added anything so far.

The following is my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

//define the dimensions of the latice
#define xmax 2
#define ymax 2

//Define parameters to obtain both the x and y coordinates of a site in the lattice at random
#define LOWER 0 
#define UPPER xmax-1 
#define ALTO ymax-1 
#define CONTAR 1

//we define the Monte Carlo steps
#define MCSS 100

//define the "empty" and "occupied" states
#define empty 0
#define occupied 1




//define the grid or lattice we will working with
int grid[xmax][ymax];



//Function that selects the x-coordinate of the chosen site randomly 
int printrandomx(int lower, int upper, int cuenta)
    {
        int m, num1;
        for (m = 0; m < cuenta ; m  ) {
        num1 = (rand() % (upper - lower   1))   lower;
        }
    return num1;
    }
    
    

//Function that selects the y-coordinate of the chosen site randomly 
    int printrandomy(int bajo, int alto, int contar)
    {
        int n,num2;
        for (n = 0; n < contar; n  ) {
        num2 = (rand() % (alto - bajo   1))   bajo;
        }
    return num2;
    }
    


//Function that generates the random coordinates of a site in the lattice
    
    int generate_coords(int red[xmax][ymax]){
        int x_coord, y_coord;
        int count = 1;
        for (int i = 0; i < xmax; i  ) {
                    for (int j = 0; j < ymax; j  ) {
                        red[i][j] = count  ;
                        printf("%d ", red[i][j]);
                    }
                    printf("\n");
                }
    
            x_coord = printrandomx(LOWER, UPPER, CONTAR);
            y_coord = printrandomy(LOWER, ALTO, CONTAR);
            printf("(x,y)=(%d,%d)\n\n", y_coord, x_coord);


            for (int i = 0; i < xmax; i  )
            {
                for (int j = 0; j < ymax; j   )
                {

                    if(x_coord == i && y_coord == j){ 
                    
                        red[y_coord][x_coord] == count; 
                        
                    }
        
                }

            }
            printf("The coordinates are (%d,%d) and the solicited matrix entry is: %d\n\n", y_coord, x_coord, grid[y_coord][x_coord]);

            if (x_coord > xmax || x_coord < 0 || y_coord > ymax || y_coord < 0) {
                printf ("Invalid coordinates given\n");
                return 1;
            }
    }



//Here starts the main function

int main(){
    
    srand(time(0));
    
    int N = xmax*ymax;
    int x = 0, y = 0;
    
    
    
    
    // Initialize lattice to be empty
    for (int i = 0; i < xmax; i  ) {
        for (int j = 0; j < ymax; j  ) {
            grid[j][i] = empty;
        }
    }
    
        
    //LOCATE AN ENTRY OF THE MATRIX RANDOMLY
        generate_coords(grid);
        
        
            
     //EVALUATE IF THE CHOSEN SITE IS EITHER EMPTY OR OCCUPIED 
     printf("IS IT OCCUPIED???\n\n");
    
                
                if (grid[y][x] == empty){

                        printf("It's empty. Let's fill it with a molecule\n\n");
                        printf("Here I will specify other conditions :)\n\n");
                        
                }else{ 
                    
                    printf("It's occupied, the trial ends. Choose another site again\n\n");
                    generate_coords(grid);
                    
                }
                

    return 0;
}


The chunk of the code that must set the initial array as empty is the following:

// Initialize lattice to be empty
    for (int i = 0; i < xmax; i  ) {
        for (int j = 0; j < ymax; j  ) {
            grid[j][i] = empty;
        }
    }

However, it seems doesn't work and I don't know why.

CodePudding user response:

Yes, you are doing it right. In this case it's a global variable so it's already initializes and you overwrite all the values in generate_coords() so it doesn't really matter.

As grid is a global variable it's implicitly zero initialized. You don't have to do anything. I recommend you avoid global variables, though, it makes your code harder to change.

If grid was a local variable (recommended) you can zero initialize it because xmax and ymax are constants:

int grid[xmax][ymax] = { 0 };

If grid xmax and ymax are variables (opposed to constants), grid would be a vla, and you now assign values to it with memset() (or memcpy() etc):

memset(grid, 0, sizeof grid);

Or, as you did, an double loop. Consider using more descriptive index variables, in this case, perhaps x and y?

    for (size_t x = 0; x < xmax; x  ) {
        for (size_t y = 0; y < ymax; y  ) {
            grid[x][y] = empty;
        }
    }

That answers the question you asked, however, I don't know wat question you meant to ask.

I refactored your code which will probably be surprising to you. Left out most of the printf() calls as they x and y when accessing the grid. Also left out the 2nd call to generate_corrds() as it seems like you wanted to run part of main() in a loop anyways.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define xmax 2
#define ymax 2

int rand_min_max(int min, int max) {
    return rand() % (max - min)   min;
}

void grid_print(int grid[xmax][ymax]) {
    for (int x = 0; x < xmax; x  )
        for (int y = 0; y < ymax; y  )
            printf("%d%s", grid[x][y], y   1 < ymax ? " " : "\n");
}

void generate_coords(int grid[xmax][ymax]) {
    memcpy(grid, (int [xmax][ymax]) {{1,2}, {3,4}}, sizeof(int [xmax][ymax]));
    int x = rand_min_max(0, xmax);
    int y = rand_min_max(0, ymax);
    grid[x][y] = xmax   ymax   1; // x and y swapped in original code, doesn't matter here but if xmax != ymax it would matter.
}

int main() {
    srand(time(0));
    int grid[xmax][ymax];
    generate_coords(grid);
    grid_print(grid);
    printf("IS IT OCCUPIED???\n\n");
    printf("It's occupied, the trial ends. Choose another site again\n\n");
}

and here is sample output:

1 5
3 4
IS IT OCCUPIED???

It's occupied, the trial ends. Choose another site again
  • Related