Why this c-program gives error when I initialize structure member outside the main function?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Why this c-program gives error when I initialize structure member outside the main function? on this date .

Why this c-program gives error when I initialize structure members (user.username and user.pin) outside the main function?, But everything becomes fine when I initialize it inside the main function.

Also is there any way to initialize a char array (member of structure)?

#include <stdio.h>

typedef struct {
    int pin;
    char username[20];
} portal;

portal user;

// user.username = "alex"; 
// user.pin[20] = 1234;  //Why this gives error when I intialize it here(i.e outside the main function)?

int main() {
    user.username = "alex"; //How to intialize a memeber(having type char) of structure?
    user.pin[20] = 1234;

    printf("WELCOME TO PORTALn");
    printf("ENTER YOUR USERNAME:n");
    scanf("%[^n]%*c", user.username);
    .
    .
    .

Actually I’m getting this output when I initialize user.username outside the main function.

enter image description here

Answer

// user.username = “alex”; // user.pin[20] = 1234; //Why this gives error when I intialize it here(i.e outside the main function)?

This is not an initialization. This is assignment statements. Outside functions you may place only declarations not statements.

Moreover even as statements they are incorrect.

Look at your structure definition

typedef struct
{
 int pin;
 char username[20];
}portal;

The data member pin has the type int. It is not an array. So this assignment

user.pin[20] = 1234;

does not make a sense. You should write at least like

user.pin = 1234;

On the other hand, the data member username is a character array. Arrays do not have the assignment operator. You have to copy a string into the character array. For example

#include <string.h>

//...

strcpy( user.username, "alex" );

But you could initialize the object user when it was declared. For example

portal user = { 1234, "alex" };

or

portal user = { .pin = 1234, .username = "alex" };

Here is a demonstrative program

#include <stdio.h>

typedef struct
{
    int pin;
    char username[20];
} portal;

portal user = { .pin = 1234, .username = "alex" };

int main(void) 
{
    printf( "pin = %d, user name = %sn", user.pin, user.username );

    return 0;
}

The program output is

pin = 1234, user name = alex