簡體   English   中英

在 C 中交換兩個結構(動態 Memory 分配)

[英]Swapping Two Structs in C (Dynamic Memory Allocation)

我正在嘗試交換 C 中的兩個結構。問題是我必須使用malloc()才能在運行時為n個結構分配 memory。 必須使用malloc()分配的 memory 的基指針訪問這些結構。 我也嘗試過類型轉換(triangle*)malloc()但這也沒有用。 誰能告訴我該怎么做?

我的代碼:

#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;
}

它沒有打印正確的 output,而是打印了垃圾值。

只需刪除tr++; 指示。

print_structs也應該固定如下:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM