I can't understand how I can initialize a char array in an array struct. I have written this code:
typedef struct tomo
{
char titolo[100];
char autore[100];
int anno_pubblicazione;
float prezzo;
} t_libro;
main(){
t_libro biblio[2];
biblio[0] = {"Guida al C", "Fabrizio Ciacchi", 2003, 45.2};
biblio[1] = {"Harry Potter e la Pietra Filosofale", "J.K.Rowling", 2003, 12.5};
}
but when i compile, it says me that before '{' an expression is expected. How i can solve it? These char arrays give me a lot of problems...
PS Ive tried also to use
biblio[0].titolo = "Guida al C";
and in this manner for the other fields of struct, but also in this manner I have an error.
biblio[0] = {"Guida al C", "Fabrizio Ciacchi", 2003, 45.2};
That is not an initialization. That is a simple assignment. You can only use initialization syntax in an initialization. It looks like this:
t_libro biblio[] = {
{"Guida al C", "Fabrizio Ciacchi", 2003, 45.2},
{"Harry Potter e la Pietra Filosofale", "J.K.Rowling", 2003, 12.5}
};
Your attempt to write
biblio[0].titolo = "Guida al C";
fails because you cannot assign to character arrays. You must either initialize them, or use a function like strcpy
.
Your main
declaration is wrong too. It should be
int main(void)
There is an other solution.
define your char array as a typedef and you could initialize your Array like this.
typedef char T_STRING[100] ;
typedef struct tomo
{
T_STRING titolo;
T_STRING autore;
int anno_pubblicazione;
float prezzo;
} t_libro;
t_libro biblio[] = {
{"Guida al C", "Fabrizio Ciacchi", 2003, 45.2},
{"Harry Potter e la Pietra Filosofale", "J.K.Rowling", 2003, 12.5}
};
On preprocessing you'r compiler will be able to initialize your array
From the respons of David Hefferman
Your attempt to write
biblio[0].titolo = "Guida al C"; fails because you cannot assign to character arrays. You must either initialize them, or use a function like strcpy.
to explain better, you have to initialize each caractere in the right memory zone.
For example
biblio[0].titolo = "Guida al C"; must be in memory to work good :
biblio[0].titolo[0] = 'G';
biblio[0].titolo[1] = 'u';
biblio[0].titolo[2] = 'i';
biblio[0].titolo[3] = 'd';
biblio[0].titolo[4] = 'a';
biblio[0].titolo[5] = ' ';
biblio[0].titolo[6] = 'a';
biblio[0].titolo[7] = 'l';
biblio[0].titolo[8] = ' ';
biblio[0].titolo[9] = 'C';
biblio[0].titolo[0] = '\0'; // (don't forget to initialize the end of your string)
this is what strcpy (or strncpy) do very well.
Ps : main () { }
gcc will automatically put int main () { } by default
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.