Search code examples
cstructure

is it possible to store several values in a structure?


I am new at c , and I was wondering if it's possible to store many values in a structure ? . I wanted to store more than 1 value of x1,y1,x2,y2. And after that I want a random value x1,y1,x2,y2. Is that possible with a struct or I need to use an other tool ?

struct test
{
    int x1;
    int y1;
    int x2;
    int y2;
};

Solution

  • It seems you need an array.

    #include <time.h> //you need this to use time(NULL)
    #include <stdlib.h> //you need this for random numbers functions
    #include <stdio.h> //you need this for printf
    
    //this is called a macro, it will get replaced by value 10 everywhere in the following code
    #define NUM_OF_VALUES 10
    
    struct test
    {
        int x1[NUM_OF_VALUES];
        int y1[NUM_OF_VALUES];
        int x2[NUM_OF_VALUES];
        int y2[NUM_OF_VALUES];
    }
    
    int main() {
    
        struct test my_test = { /* learn about initializes */ };
    
        srand(time(NULL)); //this is how you initialize random number generator to be different every time you run your code
    
        printf("Random value from x1 %d\n", my_test.x1[rand() % NUM_OF_VALUES]);
        printf("Random value from y1 %d\n", my_test.y1[rand() % NUM_OF_VALUES]);
    
        return 0;
    }
    

    Read here about how you can manually put some values in this struct for testing: https://en.cppreference.com/w/c/language/struct_initialization