【问题标题】:How can I reset a struct in a function?如何重置函数中的结构?
【发布时间】:2019-05-26 11:48:22
【问题描述】:

我主要声明了一个结构并对其进行了初始化。 然后通过一个函数我想重置这个结构,但我似乎做不到。

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

#define MAX_NOME 20
#define MAX_COGNOME 20
#define MAX_PASSAPORTO 9
#define MAX_LUOGO_DI_NASCITA 15

#define MAX_GIORNO 2
#define MAX_MESE 2
#define MAX_ANNO 4

typedef struct {
    char giorno[MAX_GIORNO+1];
    char mese[MAX_MESE+1];
    char anno[MAX_ANNO+1];
} data; //struct data/*

typedef struct {
    char nome[MAX_NOME+1];
    char cognome[MAX_COGNOME+1];
    data datadinascita;
    char luogodinascita[MAX_LUOGO_DI_NASCITA+1];
    char numeropassaporto[MAX_PASSAPORTO+1];
    int id;
} passeggero; //struct passeggero

void resetUtente();

int main() {

    passeggero utenti;

    utenti.id = 1;
    strcpy(utenti.nome, "John");
    strcpy(utenti.cognome, "McCabe");
    strcpy(utenti.datadinascita.giorno, "12");
    strcpy(utenti.datadinascita.mese, "02");
    strcpy(utenti.datadinascita.anno, "1996");
    strcpy(utenti.luogodinascita, "London");
    strcpy(utenti.numeropassaporto, "AA1234567");

    printf("USER BEFORE RESET:");
    printf("\n%d ------> %s %s - Born %s-%s-%s in %s | PASSPORT NUMBER: %s\n",utenti.id, utenti.nome,
            utenti.cognome, utenti.datadinascita.giorno, utenti.datadinascita.mese, utenti.datadinascita.anno,
            utenti.luogodinascita, utenti.numeropassaporto);

    resetUtente();

    printf("USER AFTER RESET:");
    printf("\n%d ------> %s %s - Born %s-%s-%s in %s | PASSPORT NUMBER: %s\n",utenti.id, utenti.nome,
            utenti.cognome, utenti.datadinascita.giorno, utenti.datadinascita.mese, utenti.datadinascita.anno,
            utenti.luogodinascita, utenti.numeropassaporto);

    return 0;
}

void resetUtente() {

    passeggero utenti;
    int i = 0;

    utenti.id = 0;
    utenti.nome[0] = '\0';
    utenti.cognome[0] = '\0';
    utenti.datadinascita.giorno[0] = '\0';
    utenti.datadinascita.mese[0] = '\0';
    utenti.datadinascita.anno[0] = '\0';
    utenti.luogodinascita[0] = '\0';
    utenti.numeropassaporto[0] = '\0';

}

resetUtente() 函数应将结构的所有字段设置为无,但第二个 printf 始终打印“John McCabe - 1996 年 2 月 2 日出生于伦敦 | PASSPORT NUMBER: AA1234567"

【问题讨论】:

  • resetUtente 只设置了自己的局部变量,所以调用没有效果。
  • 将地址传递给函数。你现在拥有的resetUtente 版本绝对什么都不做:它创建一个本地结构,设置一些值,然后返回。之后本地结构就消失了。
  • memset(&amp;utenti, 0, sizeof(utenti)); :-P
  • memset 到底是做什么的?我理解了我在毫无意义的功能中的错误。 :)
  • 在这种情况下将 mem 块中的每个字节设置为 0。

标签: c function struct


【解决方案1】:
void resetUtente(passeggero *u)
{
   memset(u, 0, sizeof(*u));
}

主要是

 resetUtente(&utenti);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2019-05-28
    • 2021-07-15
    • 1970-01-01
    • 2018-08-19
    • 2019-10-14
    • 2016-03-08
    相关资源
    最近更新 更多