Programming C

Tasks studies - laboratory


Project maintained by dawidolko Hosted on GitHub Pages — Theme by dawidolko

Lab08 - Unions, dynamic memory allocation

Questions

Examples

Unions

Unions are defined using the union keyword:

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

union union_name {
    int a;
    char b;
    char c[5];
    struct asd{
        float d;
    } struct_name;
} Tmyname;

int main(int argc, char const *argv[])
{
    union union_name x = {4};
    printf("%d\n", x);
    x.b = 'd';
    printf("%c\n", x);
    x.struct_name.d = 4.5;

    printf("Po zmianie ktoregos z pol struktury inne wartosci tez sa zmienione:\n");
    printf("x.a = %d", x.a);

    return 0;
}

Unions have a size equal to the largest of the stored types. In memory, the values ​​of the uni fields will be stored in a common block of memory while structures will have allocated memory locations for individual fields.

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

union myunion
{
    char a;
    int b;
    double c;
};

struct mystruct {
    char a;
    int b;
    double c;
};


int main(int argc, char const *argv[])
{
    union myunion myunion;
    struct mystruct mystruct;

    printf("ilosc bajtow ktore zajmuje unia = %i (max_zmienna=%i)\n", sizeof(myunion), sizeof(double));
    // Jeśli zmienne w strukturze posortujemy malejąco według zajmowanego miejsca w pamięci rozmiar struktury będzie mniejszy
    printf("ilosc bajtow ktore zajmuje struktura = %i (%i+%i+padding+%i)\n", sizeof(mystruct), sizeof(char), sizeof(int), sizeof(double));
    return 0;
}

The typedef keyword can be used to declare a short name for a structure or uni.

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

typedef union myunion
{
    char a;
    int b;
    double c;
} shortname;

int main(int argc, char const *argv[])
{
    union myunion x; // deklaracja uni za pomocą pełnej definicji
    shortname x1; // seklaracja uni za pomocą krótkiej definicji

    x.a = 'a';
    x1.a = 'a';
    return 0;
}

Enum

An enum type is a structure that can take on certain predetermined values. The names of these values ​​usually indicate some application state or the name of an object that allows you to clearly define what a given piece of code does. A given name hides a number. For example, color definitions in a switch statement or menu.

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

typedef enum Color
{
    RED, // odpowiada liczbie 0
    GREEN, // odpowiada liczbie 1
    BLUE // odpowiada liczbie 2
} Color;

int main(int argc, char const *argv[])
{

    Color x = GREEN;

    switch (x)
    {
    case RED:
        printf("Wybrano czerwony");
        break;
    case GREEN:
        printf("Wybrano zielony");
        break;
    case 2: // Wartości tak naprawdę są liczbammi
        printf("Wybrano niebieski");
        break;
    default:
        break;
    }

    return 0;
}

malloc and calloc

The malloc() and calloc() functions reserve a certain amount of memory. The space is freed when the free() function is used

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

int *alocateTabMalloc(int a)
{
    int rozmiar_tablicy = a * sizeof(int); // ilość elementów * rozmiar jednego elementu
    int *ptr = malloc(rozmiar_tablicy);
    return ptr;
}

int *alocateTabCalloc(int a)
{
    int *ptr = calloc(a, sizeof(int)); // alokuje określoną ilość w pamięci danego typu i ustawia wartości w pamięci na 0.
    return ptr;
}

int main(int argc, char const *argv[])
{
    int *tab = alocateTabMalloc(4); // utworzenie tablicy na 4 zmienne typu int
    for (size_t i = 0; i <= 5; i++)
    {
        if (i > 3)
        {
            printf("tab[%d] = %d (poza tablica)\n", i, tab[i]);
            continue;
        }
        printf("tab[%d] = %d\n", i, tab[i]);
    }

    int *tab2 = alocateTabCalloc(4); // utworzenie tablicy na 4 zmienne typu int
    for (size_t i = 0; i <= 5; i++)
    {
        if (i > 3)
        {
            printf("tab2[%d] = %d (poza tablica)\n", i, tab2[i]);
            continue;
        }
        printf("tab2[%d] = %d\n", i, tab2[i]);
    }

    // kopiuje wskaźnik do tablicy tab2
    int *ptr2 = tab2;
    // zwalniam pamięć
    free(tab2);
    // Wypisuję zawartość pamięci
    for (size_t i = 0; i <= 5; i++)
    {
        printf("ptr2[%d] = %d (zwomnione miejsce)\n", i, ptr2[i]);
    }

    return 0;
}

Tasks

We want to create an array that accepts values ​​of various types. Then a function that will print the contents of the array.

Task 1

Create an enumeration type var_type containing values ​​INT, FLOAT, CHAR.

Task 2

Create a structure var that will store the type of the variable. And the value of the variable. The type of the variable is an enumeration type, and for storing the value, create a union with the types as in the previous task.

Task 3

Create a function setInt() setFloat() setChar() that takes two arguments, a pointer to the variable var and the value of the variable. The functions set the values ​​of the variable var accordingly.

Task 4

Create an array containing 10 values ​​of type var. Fill the array of values ​​first with numbers from 1 to 10. Fill the array with values ​​A, B, C, D …

Task 5

Create a varToString() function that returns a pointer to a string. For example, if var stores the value 100, varToString() should return a pointer to an array that stores the string “100”. Use the sprintf()

Task 6

Print the contents of the arrays using the functions you created.