结构体初始化所遇到的问题

一:变量的赋值和变量的初始化问题

变量赋值和变量初始化不是一回事!

变量赋值发生在运行期,其写法遵循赋值语法规定。

变量初始化发生在编译期或运行期,其写法遵循初始化列表语法规定。

局部变量是在函数内部所以它既可以初始化也可以赋值。

#include<stdio.h>
#include<string.h>
typedef struct Fil{
    char *homework;  // 需要申请内存,否则会报错。 
    int num;
    char teacher[50];
}file;

file homework;  
homework.num=4;
homework.teacher="Ms zhang";

int main()
{
    printf("the homework is %s,the num is %d.",homework.teacher,homework.num);
    return 0;
}

报错原因:"[Error] expected '=', ',', ';', 'asm' or '__attribute__' before '.' token"

file homework;语句中已经把homework中的成员变量初始化了,因为全局变量如果不显式初始化的话 会自动初始化为0。在给成员变量赋值的时候只能在函数内,所以会报错。

二:字符指针赋值问题

#include<stdio.h>
#include<string.h>
typedef struct Fil{
    char *homework;  // 需要申请内存,否则会报错。 
    int num;
    char teacher[50];
}file;

int main()
{
    file homework;
    homework.homework="english";  // 不能直接赋值 
    homework.num=4;
    homework.teacher="Ms zhang";
    printf("the homework is %s,the num is %d,the teacher is %s.",homework.homework,homework.num,homework.teacher);
    return 0;
}

问题:1.在结构体中给指针赋值时不能直接赋值,而应该先分配内存,再赋值。homework.homework=(char*)malloc(sizeof(char)*8);

   2.在结构体中给指针和数组赋值时,不能直接赋值,应该用strcpy()函数。

三:正确的赋值和初始化

#include<stdio.h>
#include<string.h>
typedef struct Fil{
    char *homework;  // 需要申请内存,否则会报错。 
    int num;
    char teacher[50];
}file;


file housework;  

int main() { homework.homework=(char*)malloc(sizeof(char)*8); // 结构体中字符串在堆上申请内存然后再赋值 strcpy(homework.homework,"english"); homework.num=4; strcpy(homework.teacher,"Ms zhang"); printf(" the homework is %s the num is %d the teacher is %s ",homework.homework,homework.num,homework.teacher); printf(" the housework is %s the num is %d the teacher is %s ",housework.homework,housework.num,housework.teacher); return 0; }

 

原文地址:https://www.cnblogs.com/ligei/p/12486363.html