簡體   English   中英

我不能在 c 中將一個結構分配給另一個

[英]i can't assign one struct to another in c

我有 2 個結構,我想將一個結構分配給另一個結構,但是當我打印結果時,它會打印廢話,功能:“ver_tope”負責執行此操作,我在做什么壞事?,這是代碼:

#include <stdio.h>
#include <stdlib.h>
#define TAM 4

typedef struct{
        char nomyap[40];
        int edad;

}t_info;

typedef struct {
    t_info pila [TAM];
    int tope;

}t_pila;

void ver_tope(const t_pila *p, t_info *d);

int main()
{
    t_pila pila;
    t_info info;
    //I CHARGE BOTH STRUCTS

    ver_tope(&pila, &info);

    return 0;
}

void ver_tope(const t_pila *p, t_info *d)
{
   *d = p->pila[(p->tope)-1];
    return ;
}

嘗試在 main() 中為 pila.tope 添加一個初始化,例如:

...    //I CHARGE BOTH STRUCTS
pila.tope =2;
ver_tope(&pila, &info);
...

這停止了​​分段錯誤......

int main()
{
    t_pila pila;
    t_info info;
    ver_tope(&pila, &info);
    return 0;
}

您尚未初始化任一變量。 由於pila是作業的來源,您可以執行以下操作:

int main()
{
    t_pila pila = { 0 };
    pila.tope = 1;
    t_info info;
    ver_tope(&pila, &info);
    return 0;
}

在這里,我默認初始化pila ,然后將其tope成員設置為1 我沒有初始化info因為ver_tope分配給它。 如果將ver_tope轉換為返回t_info的函數會更清楚。

暫無
暫無

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

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