C语言开发,结构体的定义与使用,动态开辟内存,指针

文章目录

  • C语言开发,结构体的定义与使用,动态开辟内存,指针
    • 1.定义与使用
    • 2.结构体开辟内存,指针
    • 3.数组
    • 4.枚举

C语言开发,结构体的定义与使用,动态开辟内存,指针

1.定义与使用

//
// Created by MagicBook on 2023-10-22.
//
#include 
#include 
#include 
#include 

//C语言结构体相当java中的类
struct Test {
    char a[10];
    int b;
    char c;
} qfh = {"1122", 33, 's'};

int main() {
    //没有默认值,系统值
    struct Test test;
    printf("%s,%d,%c\n", test.a, test.b, test.c);
    //赋值
    strcpy(test.a, "111");
    test.b = 2;
    test.c = 'a';
    return 0;
}

2.结构体开辟内存,指针

//
// Created by MagicBook on 2023-10-22.
//
#include 
#include 
#include 
#include 

typedef struct Test Test;
//C语言结构体相当于java中的类
struct Test {
    char a[10];
    int b;
    char c;
} qfh = {"1122", 33, 's'};

int main() {
    //内存栈中
    struct Test test = {"1122", 33, 's'};
    //指针
    struct Test *test1 = &test;
    test1->b = 3;
    strcpy(test1->a, "2113");
    printf("%s,%d\n", test1->a, test1->b);

    struct Test *test2 = malloc(sizeof(Test));
    strcpy(test2->a, "1222");
    printf("%s\n", test2->a);

    free(test2);
    test2 = NULL;
    return 0;
}

3.数组

//
// Created by MagicBook on 2023-10-22.
//
#include 
#include 
#include 
#include 

typedef struct Test Test;
//C语言结构体相当于java中的类
struct Test {
    char a[10];
    int b;
} qfh = {"1122", 33};

int main() {
    struct Test test[3] = {
            {"12", 2},
            {"12", 2},
            {"12", 2},
    };
    struct Test test1 = {"!2", 2};
    test[1] = test1;

    //动态内存,默认指向数组首地址,第一个元素
    struct Test *test2 = malloc(sizeof(struct Test) * 10);

    strcpy(test2->a,"222");
    free(test2);
    test2 = NULL;

    return 0;
}

4.枚举

//
// Created by MagicBook on 2023-10-22.
//
#include 
#include 
#include 
#include 

enum Test {
    ONE = 1,
    TWO,
    THIRD
};

int main() {
    enum Test test1 = ONE;
    enum Test test2 = TWO;
    enum Test test3 = THIRD;
    printf("%d,%d,%d\n", test1, test2, test3);

    return 0;
}

你可能感兴趣的:(Android进阶训练营,1024程序员节)