To do it the way you want it to be like this:
#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);
}
See running on ideone .
You can not initialize the structure in itself, and it does not even make sense.
It is true that this is not usually done in real application. You're wasting memory. Not that it is wrong, in fact it has cases that is best because it avoids allocation and release of unnecessary memory, which is something that is expensive and can inadvertently generate errors. There are those who prefer to do so in some cases. For exercise it is a good start to do 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);
}
See working on ideone .
The 2 in malloc()
is because the string that will be used has 1 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, it takes a lot of care to use it correctly, including when it resolves to change the string value. Alias, it should be constant, but I will not try to solve all the questions, you do not have to select any to solve. This works, and it's strictly correct, but it's not the ideal way to produce real code.
Note also that I did not give free()
to rent some, this makes leaking memory. For a simple case like this, no problem, but in a real program would need to do at the right time and place, which is not easy to manage and depends on a number of factors.
In fact, the ideal even there may be to use union
, but it is too advanced and depends on requirements, not something for an exercise.