关于c语言定义变量

本文探讨了C语言中变量定义的位置对程序运行的影响。通过具体示例说明,在某些情况下,变量定义的位置可能会导致程序出现错误。特别是对于结构体指针的定义位置,作者发现不同的位置会导致不同的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

about the place of defining variable in c program!

一直以来的学习中关于变量的定义都是在使用之前,也就是说使用之前定义了都没问题,但是最近练习中却发现事实并非如此。

such as the example  following:

#include <stdio.h>

struct date
{
    int month;
    int day;
    int year;
}date1;
struct date date2;
struct student
{
    char num[11];
    char name[11];
    char sex;
    struct date birthday;
}qjl[3]={{"20041102215","qujl1",'M',8,23,1985},
         {"20041102215","qujl2",'F',8,23,1985},
         {"20041102215","qujl3",'M',8,23,1985}
         };
main()
{
    struct date date4;
    struct student *p;                 //●
    date4.month=6;
    date4.day=10;
    date4.year=3005;
    /*date4={6,10,3006};*/       /*错误赋值方法*/
    printf("%d-%d-%d/n",date4.year,date4.month,date4.day);

    printf("NO.           NAME       SEX /n");
    for(p=qjl;p<qjl+3;p++)
        printf("%-19s   %-11s%-2c/n",p->num,p->name,p->sex);
    getch();

in the example ,when i define    struct  student *p;  in the head of the program,it's true ,but when i define it   between        the sentence  printf("NO.               NAME              SEX/n");and  the for cyclic ,it will be false.

I don't know the reason  of this instance,mybe  i  will know it   later.

if  you pass by my blog ,and you know the reason,please tell me!Thank you forver!

### C语言结构体定义的方法 #### 定义并声明结构体变量 可以直接在定义结构体类型的同时创建该类型的多个实例对象。这种方式简洁明了,在实际编程中非常实用。 ```c struct data { char* name; int age; } sum1, sum2; // 同时定义名为sum1和sum2的data型变量[^1] ``` #### 基本的标准结构体定义法 先单独描述数据成员构成的新复合类型,之后再基于此新类型来初始化具体的实体单元。 ```c // 首先定义一个新的结构体类型student struct student{ char no[20]; char name[20]; char sex[5]; int age; }; // 接着利用上述自定义的数据类型构建具体的学生记录 struct student stu1, stu2; // 此处stu1与stu2均为student结构体变量[^2] ``` #### 复杂嵌套式的结构体设计模式 允许在一个结构体内包含另一个完整的结构体作为其组成部分之一,从而实现更加复杂的数据关联关系表达需求。 ```c #include<stdio.h> #define NAME_MAX_LEN 12 struct date {/*...*/}; // 假设这里已经正确定义了一个表示日期的结构体date struct student { char name[NAME_MAX_LEN]; char sex; struct date birthday; float score[4]; }; ``` #### 使用typedef简化语法糖衣 通过`typedef`关键字可以给现有的结构体型赋予更易读的名字标签,使得后续代码编写过程中的可维护性和直观程度得到显著提升。 ```c typedef struct tag_student { /* 成员列表 */ } STUDENT; STUDENT s1, s2; // 不必每次都重复写入'struct'前缀即可完成相同操作 ``` #### 匿名结构体及其应用场合 当不需要为某个特定用途而专门命名新的结构体类别时,则可以选择省略掉名字部分直接使用匿名形式。 ```c union { // 或者也可以是其他种类的关键字比如enum/struct long l; double d; } u; u.d = 3.1415926L; printf("%f\n", u.d); ``` #### 构造带参数初始化器的结构体 对于某些场景下希望能够在声明阶段就给予各字段初始值的情况而言,可以在大括号内按照顺序指定相应数值来进行快速填充设置。 ```c struct point p = { .x=10 , .y=-7 }; /* 等价于下面这种传统做法 */ struct point q; q.x = 10; q.y = -7; ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值