What is the use of struct in c?

Asked

Viewed 434 times

1

I’ve learned how to use the command in a code, but I still don’t understand exactly what it’s for. Could someone explain to me, with examples if possible, their usefulness?

  • 1

    struct is not a command, it is a data type that basically serves roughly to group other data types

  • Possible duplicate of Struct definition in C

  • @Samuelives was my mistake, I was very sleepy at the time, I ended up writing nonsense

1 answer

6


The struct is basically used to group variables that have a common goal and create new types of data. Technically, the struct will physically align this data in memory allowing it to be accessed by a single access point. For example: If you need to store a person’s data as 'name', 'age', 'gender', etc.. define a struct named 'person' with the data you need.

struct pessoa {
  char *nome;
  unsigned int idade;
  char genero[1]; // M ou F
};

// Declaração da variável p utilizando a struct pessoa
struct pessoa p;

// Definição dos valores. 
p.nome = "Joao";  
p.idade = 12;
p.genero = 'M';
  • Obgd msm, now I understood, I did not know that the command was able to align the data in memory. I’d give you an upvote if I could, but you know, less than 15 points kkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.