简体   繁体   English

为什么当我在主 function 之外初始化结构成员时,这个 c 程序会出错?

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

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.为什么当我在main function 之外初始化结构成员( user.usernameuser.pin )时,这个 c 程序会出错?但是当我在main function 中初始化它时,一切都会好起来的。

Also is there any way to initialize a char array (member of structure)?还有什么方法可以初始化 char 数组(结构成员)?

#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 PORTAL\n");
    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.实际上,当我在main function 之外初始化user.username时,我得到了这个 output。

在此处输入图像描述

// user.username = "alex"; // user.username = "alex"; // user.pin[20] = 1234; // user.pin[20] = 1234; //Why this gives error when I intialize it here(ie 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 .数据成员pin的类型为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.另一方面,数据成员username是一个字符数组。 Arrays do not have the assignment operator. Arrays 没有赋值运算符。 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.但是您可以在声明 object user时对其进行初始化。 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 = %s\n", user.pin, user.username );

    return 0;
}

The program output is程序 output 是

pin = 1234, user name = alex

Global variables can be initialized as the point of definition, but not as stand alone statements:全局变量可以初始化为定义点,但不能作为独立语句:

portal user = { 1234, "alex" };  // definition with an initializer

user.pin = 1234;        // assignment is invalid outside a function
user.username = "Alex"; // assignment is invalid outside a function and assigning to an array is invalid as well

The structure members can be set inside a function, but arrays contents cannot be assigned with the = operator, you need to assign array elements explicitly or use a function call:结构成员可以在 function 中设置,但 arrays 内容不能用=运算符分配,您需要显式分配数组元素或使用 function 调用:

int main() {
    char extra[20];

    user.pin = 1234;         // OK

    user.username[0] = 'A';  // tedious, but OK
    user.username[0] = 'l';
    user.username[0] = 'e';
    user.username[0] = 'x';
    user.username[0] = '\0'; 

    strcpy(user.username, "Alex"); // OK if username has at least 5 elements

    snprintf(user.username, sizeof user.username, "%s", "Alex"); // overkill, but OK

    // read values from stdin:
    // scanf will return the number of members successfully converted:
    switch (scanf("%d%19s%19[^\n]", &user.pin, user.username, extra)) {
      case EOF:
        printf("premature end of file\n");
        break;
      case 0:
        printf("input is not a number for user.pin\n");
        break;
      case 1:
        printf("user.pin=%d, no input for user.username\n", user.pin);
        break;
      case 2:
        printf("user.pin=%d, user.username=%s\n", user.pin, user.username);
        break;
      case 3:
        printf("user.pin=%d, user.username=%s, extra input=%s\n", user.pin, user.username, extra);
        break;
    }
    return 0;
}

In C, outside of functions, you can have only declarations and preprocessor directives.在 C 中,在函数之外,您只能有声明和预处理器指令。 The source text user.username = "alex";源文本user.username = "alex"; is a statement, as is user.pin[20] = 1234;是一个语句, user.pin[20] = 1234; . . The compiler error message occurs because the compiler is expecting a declaration, and your statements do not fit what it is expecting.出现编译器错误消息是因为编译器需要声明,而您的语句不符合预期。

To initialize objects as you are defining them, you use a syntax for initialization with the definition rather than writing separate statements.要在定义对象时对其进行初始化,请使用带有定义的初始化语法,而不是编写单独的语句。 user could be defined and initialized with either of: user可以使用以下任一方式定义和初始化:

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

Although definitions use = in initialization, this is not an assignment.尽管定义在初始化中使用= ,但这不是赋值。 It is a different use of the = symbol for a similar effect (put this value in that place).这是对类似效果的=符号的不同用法(将此值放在那个位置)。 Another difference is that, in an initialization, you can use a string literal to initialize a character array.另一个区别是,在初始化中,您可以使用字符串文字来初始化字符数组。 In a statement, you cannot.在一份声明中,你不能。

Another way to give initial values to user would be to write statements inside main :user提供初始值的另一种方法是在main中编写语句:

int main(void)
{
    strcpy(user.username, "alex");
    user.pin = 1234;
    …
}

That struct member was already initialised.该结构成员已经初始化。 When you do it outside main the compiler can optimise it by setting it to the string literal straight away.当您在main之外执行此操作时,编译器可以通过立即将其设置为字符串文字来对其进行优化。

If main is entered, then it's too late to initialise.如果输入了main ,那么初始化为时已晚。 The compiler does not make the assumption that main is guaranteed to be called or called immediately.编译器不假设main保证被调用或立即调用。 Therefore the statement within main is not initialisation but assignment.因此main中的语句不是初始化而是赋值。 You cannot assign to a character array, that's what strcpy and related functions are for.您不能分配给字符数组,这就是strcpy和相关函数的用途。

This should work:这应该有效:

strcpy(user.username, "Alex")

or或者

snprintf(user.username, sizeof user.username, "Alex");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C程序的函数似乎总是返回true,但是我不明白为什么 - C-program's function seems to return always true, but I don't see why 数组中struct中的c ++成员函数指针给出了编译错误 - c++ member function pointer in struct in array gives compilation error 搜索整个数组以查找字符序列的C程序 - C-program that searches through an array to find a sequence of characters (C程序)关于数组地址的示例代码 - (C-Program) example Code about Array Address 运行Python程序时,弹出错误“外部函数返回” - When running a Python Program, the error “'return' outside function” pops up 在D中初始化结构成员数组 - Initialize Structure Member Arrays in D 为什么在尝试初始化数组时出现错误? - Why I get error when I try to initialize an array? 为什么当我打印由“主”function 交付的二维数组时出现段错误 - why i get segment error when i print 2-D array which is delivery by the "main" function C:尝试初始化结构中的char数组时分配错误中的类型不兼容 - C: Incompatible types in assignment error when trying to initialize char arrays within a structure 如何初始化结构的int数组成员? - How to initialize an int array member of a structure?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM