To do it the way you want it is this way:
#include<stdio.h>
#define tam 100
typedef struct {
char nome[51];
char curso[51];
char cota[51];
int matricula;
int coef;
} TipoAluno;
int main() {
TipoAluno aluno = {
.nome = "A",
.curso = "B",
.cota = "C",
.matricula = 1
};
printf("%s", aluno.nome);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
You can’t initialize the structure itself, and it doesn’t make sense.
It is true that it is not often done so in real application. You are wasting memory. Not that it’s wrong, actually there are cases that are better this way because it avoids unnecessary memory allocation and release, which is something that costs expensive and can unintentionally generate errors. There are those who prefer to do so in some cases. For exercise it is good to start doing so, but the most common is to allocate the string separately according to the required size.
Then you could do:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define tam 100
typedef struct {
char *nome;
char *curso;
char *cota;
int matricula;
int coef;
} TipoAluno;
int main() {
TipoAluno aluno = {
.nome = malloc(2),
.curso = malloc(2),
.cota = malloc(2),
.matricula = 1
};
strcpy(aluno.nome, "A");
strcpy(aluno.curso, "B");
strcpy(aluno.cota, "C");
printf("%s", aluno.nome);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Paragraph 2 in malloc()
is because the string which will be used is 1 in size (needs one more for the terminator). It would not make sense to allocate more than needed.
Note that this is a very naive implementation, has a lot of care to use correctly, including when you decide to change the value of string. By the way, it should be constant, but I’m not going to try to solve all the questions, there’s no reason to select one to solve. This works, and is strictly correct, but is not the ideal form for real code in production.
Note also that I did not give free()
in renting some, it leaks memory. For such a simple case, it is no problem, but in a real program would need to do in the right place and time, which is not easy to manage and depends on a number of factors.
In fact, the ideal even then would be to use a union
, but it is something too advanced and depends on the requirements, it is not something for an exercise.
Initialize the struct on main... Try to see if this is it!
– Maurício Z.B
Better explain the purpose of the code
– Maurício Z.B
i have to create this Tipoaluno and record several students of this type in a file, only that the fields name and course for example will not be used for search and search, so the teacher gave as dirt put any character in the variable.
– Daniel Saldanha
Try to see the code I posted... If your teacher sent it by any character... I recommend you do it in the main and not within the struct.
– Maurício Z.B