C语言各种类型变量初始化
所属分类 c
浏览量 772
全局 和 静态变量会自动初始化为零值
局部变量需要显示初始化,否则值不确定
定义时初始化
int i = 0;
float f = 0.00f;
double d = 0.00;
char ch = '\0';
char str[10] = "";
char str[10];
memset(str, 0, sizeof(str));
memset 按字节进行填充 注意是按字节填充
int num;
memset(&num, 0, sizeof(int));
printf("step1=%d\n", num);
memset(&num, 1, sizeof(int));
printf("step2=%d\n", num);
step1 = 0
step2 = 16843009
int 4个字节
00000000 00000000 00000000 00000000
00000001 00000001 00000001 00000001
char year[4+1];
memset(year, 0, sizeof(year));
strcpy(year,"2021");
指针一般初始化为 NULL
int *pnum = NULL;
int num = 0;
pnum = &num ;
typedef struct student
{
int id;
char name[20];
}Student;
Student student1;
memset((char *)&student1, 0, sizeof(student1));
https://gitee.com/dyyx/hellocode/blob/master/web/tech/c/demo/init.c
#include
#include
#include
typedef struct student
{
int id;
char name[20];
}Student;
int main(int argc,char *argv[]){
int i = 0;
float f = 0.00f;
double d = 0.00;
char ch = '\0';
char str[3] = "";
char str2[] = "hello";
char str3[7];
memset(str3, 0, sizeof(str3));
char str4[7]={0};
int num;
memset(&num, 0, sizeof(int));
printf("step1=%d\n", num);
memset(&num, 1, sizeof(int));
// 16843009
// memset 按字节填充
// 00000001 00000001 00000001 00000001
printf("step2=%d\n", num);
char year[4+1];
memset(year, 0, sizeof(year));
strcpy(year,"2021");
printf("year=%s\n",year);
int *pnum = NULL;
pnum = &num ;
printf("%p\n",pnum);
Student student1;
memset((char *)&student1, 0, sizeof(student1));
printf("id=%d, name=%s\n", student1.id,student1.name);
Student student2={0};
printf("id=%d, name=%s\n", student2.id,student2.name);
}
上一篇
下一篇
c语言获取时间字符串
c语言中命令行参数
c 和 Java 格式化输出
grafana忘记密码重置
sizeof与strlen的区别
size_t和int区别