Home > Blockchain >  Swapping Two Structs in C (Dynamic Memory Allocation)
Swapping Two Structs in C (Dynamic Memory Allocation)

Time:10-10

I am trying to swap two structs in C. The issue is I have to use malloc() in order to allocate memory for n number of structs during run-time. The structs have to accessed using the base pointer of the memory allocated by malloc(). I also tried typecasting (triangle*)malloc() But that didn't work either. Can anyone tell me how to do this?

My Code:

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

struct triangle
{
    int a;
    int b;
    int c;
};
typedef struct triangle triangle;

void swapStructs(triangle *a, triangle *b)
{
    triangle temp = *a;
    *a = *b;
    *b = temp;
}

void print_structs(triangle *tr, int n)
{
    printf("VALUES BEFORE SWAPPING...\n");
    for(int i=0; i<n; i  )
    {
        printf("A[%d]: %d\n", i ,tr->a);
        printf("B[%d]: %d\n", i ,tr->b);
        printf("C[%d]: %d\n", i ,tr->c);
        tr  ;
    }
    swapStructs(&tr[0], &tr[1]);

    printf("VALUES AFTER SWAPPING...\n");
    for(int i=0; i<n; i  )
    {
        printf("A[%d]: %d\n", i ,tr->a);
        printf("B[%d]: %d\n", i ,tr->b);
        printf("C[%d]: %d\n", i ,tr->c);
        tr  ;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    triangle *tr = malloc(n * sizeof(triangle));

    for (int i = 0; i < n; i  )
    {
        scanf("%d %d %d", &tr[i].a, &tr[i].b, &tr[i].c);
    }
    swapStructs(&tr[0], &tr[1]);

    print_structs(tr, n);

    return 0;
}

Rather than printing the correct output, it printed garbage values.

CodePudding user response:

Just remove the tr ; instructions.

Also the print_structs should be fixed as follow:

void print_structs(triangle *tr, int n)
{
    printf("VALUES BEFORE SWAPPING...\n");
    for(int i=0; i<n; i  )
    {
        printf("A[%d]: %d\n", i ,tr[i].a);
        printf("B[%d]: %d\n", i ,tr[i].b);
        printf("C[%d]: %d\n", i ,tr[i].c);
    }
    swapStructs(&tr[0], &tr[1]);

    printf("VALUES AFTER SWAPPING...\n");
    for(int i=0; i<n; i  )
    {
        printf("A[%d]: %d\n", i ,tr[i].a);
        printf("B[%d]: %d\n", i ,tr[i].b);
        printf("C[%d]: %d\n", i ,tr[i].c);
    }
}
  • Related